Android JSONObject:将数组添加到 put 方法

jsAndroid

1个回答

写回答

xhh_2018

2025-07-06 22:05

+ 关注

Android
Android

使用 Android JSONObject 类的 put 方法可以将数组添加到 JSON 对象中。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据交互。JSONObject 是 Android 提供的一个用于处理 JSON 数据的类,它可以将 JSON 数据转化为 Java 对象,也可以将 Java 对象转化为 JSON 数据。

在使用 JSONObject 的 put 方法添加数组时,需要先创建一个 JSONArray 对象,并将数组中的元素添加到 JSONArray 中,然后再将 JSONArray 对象添加到 JSONObject 中。

下面是一个示例代码,演示了如何使用 JSONObject 的 put 方法将数组添加到 JSON 对象中:

Java

import org.JSon.JSONArray;

import org.JSon.JSONException;

import org.JSon.JSONObject;

public class MAInActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setcontentView(R.layout.activity_mAIn);

try {

// 创建一个 JSONObject 对象

JSONObject JSonObject = new JSONObject();

// 创建一个数组

String[] fruits = {"Apple", "banana", "orange"};

// 创建一个 JSONArray 对象

JSONArray JSonArray = new JSONArray();

// 将数组中的元素添加到 JSONArray 中

for (String fruit : fruits) {

JSonArray.put(fruit);

}

// 将 JSONArray 对象添加到 JSONObject 中

JSonObject.put("fruits", JSonArray);

// 输出 JSONObject

Log.d("MAInActivity", JSonObject.toString());

} catch (JSONException e) {

e.printStackTrace();

}

}

}

上述代码中,首先创建了一个 JSONObject 对象 JSonObject。然后创建了一个字符串数组 fruits,其中包含了三种水果。接着创建了一个 JSONArray 对象 JSonArray,并使用 for 循环将数组中的元素逐个添加到 JSonArray 中。最后将 JSonArray 添加到 JSonObject 中,并使用 Log 输出 JSonObject 的内容。

通过运行上述代码,可以在 Logcat 中看到输出的 JSONObject 内容如下:

{

"fruits": [

"Apple",

"banana",

"orange"

]

}

上述代码演示了如何使用 JSONObject 的 put 方法将数组添加到 JSON 对象中。这在实际开发中经常用到,特别是在与后端进行数据交互时,可以方便地将数组数据打包成 JSON 对象,再传输给后端服务器

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号