我正在try 遍历下面的JSON

{
    "dataArray": [{
        "A": "a",
        "B": "b",
        "C": "c"
    }, {
        "A": "a1",
        "B": "b2",
        "C": "c3"
    }]
}

到目前为止我得到的是:

JSONObject jsonObj = new JSONObject(json.get("msg").toString());

for (int i = 0; i < jsonObj.length(); i++) {
    JSONObject c = jsonObj.getJSONObject("dataArray");

    String A = c.getString("A");
    String B = c.getString("B");
    String C = c.getString("C");

}

有什么 idea 吗?

推荐答案

In your code the element dataArray is an array of JSON objects, not a JSON object itself. The elements A, B, and C are part of the JSON objects inside the dataArray JSON array.

You need to iterate over the array

public static void main(String[] args) throws Exception {
    String jsonStr = "{         \"dataArray\": [{              \"A\": \"a\",                \"B\": \"b\",               \"C\": \"c\"            }, {                \"A\": \"a1\",              \"B\": \"b2\",              \"C\": \"c3\"           }]      }";

    JSONObject jsonObj = new JSONObject(jsonStr);

    JSONArray c = jsonObj.getJSONArray("dataArray");
    for (int i = 0 ; i < c.length(); i++) {
        JSONObject obj = c.getJSONObject(i);
        String A = obj.getString("A");
        String B = obj.getString("B");
        String C = obj.getString("C");
        System.out.println(A + " " + B + " " + C);
    }
}

prints

a b c
a1 b2 c3

I don't know where msg is coming from in your code snippet.

Json相关问答推荐

PowerShell:将Invoke-WebRequest与变量一起使用

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

如何在Vega中使标记的符号在鼠标指针悬停时可点击

在Ansible中从json中提取特定数据

来自json的可分析的构建报告

当 JSON 字段名称有空格时,ABAP 中的 JSON 反序列化

在 postgres 14 中将记录转换为所需的 json 格式

德纳比可视化区域图表 Power BI

带有 API 测试的 Typescript JSON 模式验证

Oracle json 对象的最后一个值不在引号中

无法在 json --data 中使用变量

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

JSON Schema 与 XML Schema 的比较及其future

如何使用 CORS 实现 JavaScript Google Places API 请求

Java的JSON字符串整洁/格式化程序

Java循环遍历Json数组?

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

Newtonsoft 对象 → 获取 JSON 字符串

使用 JSONArray 和 JSONObject 进行 Foreach