Android 之 数组转JSON

本文介绍如何在Android开发中将数组转换成JSON格式,并通过示例展示了两种不同的实现方式。第一种方式是直接构造JSON对象和数组,第二种方式是通过遍历列表来构建JSON数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android 之
数组转JSON
post 多层级 Body 上传服务器

image.png

Android 之 数组转JSON:

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username", "mobile");
            jsonObject.put("password", "password");
            JSONArray jsonArray = new JSONArray();

            JSONObject tmpObj = null;
            tmpObj = new JSONObject();
            tmpObj.put("name", "张三");
            tmpObj.put("sex", "男");
            tmpObj.put("age", "16");

            jsonArray.put(tmpObj);

            jsonObject.put("personInfos", jsonArray); // 获得JSONObject的String

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("111111 LogonActivity>>", "jsJson ====:" + jsonObject);

Log打印:

image.png

{
    "username": "mobile",
    "password": "password",
    "personInfos": [{
        "name": "张三",
        "sex": "男",
        "age": "16"
    }]
}

image.png

第二种写法:

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "mobile");
        jsonObject.put("password", "password");

        JSONArray jsonArray = new JSONArray();
        List personList = new ArrayList();  //中已经装载好了数据:
        JSONObject tmpObj = null;
        int count = personList.size();
        for(int i = 0; i < count; i++) {
            tmpObj = new JSONObject();
            tmpObj.put("name", personList.get(i).name);
            tmpObj.put("sex", personList.get(i).sex);
            tmpObj.put("age", personList.get(i).age);
            jsonArray.put(tmpObj);
//            tmpObj = null;
        }
        Log.d("111111 LogonActivity>>", "jsJson ====:" + jsonObject);

。。。

### 将 Android 中的字符串解析为 JSON 数组Android 开发中,可以通过 `org.json.JSONArray` 类来处理 JSON 数据。如果接收到的是一个表示 JSON 数组的字符串,则可以直接将其传递给 `JSONArray` 构造函数以完成解析操作[^3]。 以下是具体的实现方式: #### 解析 JSON 字符串为 JSONArray 的代码示例 假设有一个 JSON 字符串如下所示: ```json ["item1", "item2", "item3"] ``` 可以使用以下代码片段对其进行解析并访问其中的内容: ```java import org.json.JSONArray; public class JsonArrayExample { public static void main(String[] args) { try { String jsonString = "[\"item1\", \"item2\", \"item3\"]"; // 原始 JSON 字符串 JSONArray jsonArray = new JSONArray(jsonString); // 创建 JSONArray 实例 // 遍历 JSONArray 并获取其内容 for (int i = 0; i < jsonArray.length(); i++) { System.out.println("Item at index " + i + ": " + jsonArray.getString(i)); } } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码展示了如何将 JSON 字符串化为 `JSONArray` 对象,并通过索引来提取数组中的每一项数据。 需要注意的是,在实际应用中可能遇到更复杂的嵌套结构或者键值对形式的数据(即 JSONObject)。此时应先将整个响应封装到 JSONArray 或者 JSONObject 中再逐步拆解[^4]。 另外,当面对来自网络请求或其他外部源输入时,请务必验证传入参数的有效性和合法性以防止潜在的安全隐患如 SQL 注入等问题发生[^1]。 #### 使用第三方库 Gson 进行换 除了原生支持外,还可以借助像 Google 提供的开源项目 **Gson** 来简化这一过程。它允许开发者更加灵活地定义自定义序列化/反序列化的逻辑[^2]。 下面是一个简单的例子展示怎样利用 Gson 把 List<String> 序列化成 JSON 表达式以及反过来的过程: ```java import com.google.gson.Gson; import java.util.Arrays; import java.util.List; public class GsonListToJsonExample { public static void main(String[] args){ List<String> stringList = Arrays.asList("element1","element2"); // Convert from list to json array as a string. Gson gson=new Gson(); String jsonString=gson.toJson(stringList); System.out.println("JSON Array:"+jsonString); // Now convert it back to the list of strings. @SuppressWarnings("unchecked") List<String> newList=(List<String>)gson.fromJson(jsonString,List.class); System.out.println(newList.get(0)); // Output: element1 } } ``` 此段程序说明了即使不依赖于标准库也可以高效达成目标的同时还提供了额外的功能选项比如类型适配器等等。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值