java - 在 JSON 对象中解析 JSON 数组

标签 java json parsing

我有一些具有以下结构的 JSON:

{"source":[
           {"name":"john","age":20},
           {"name":"michael","age":25},
           {"name":"sara", "age":23}
         ]
}

我已将此 JSON 字符串命名为 mainJSON。我正在尝试使用以下 Java 代码访问元素“名称”和“年龄”:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
for (int i = 0; i < jsonMainArr.length(); i++) {  // **line 2**
     JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
     String name = childJSONObject.getString("name");
     int age     = childJSONObject.getInt("age");
}

我看到的是第 2 行的以下异常:

org.json.JSONException: JSONArray initial value should be a string or collection or array.

请指导我在哪里犯了错误以及如何纠正这个错误。

最佳答案

mainJSON.getJSONArray("source") 返回一个 JSONArray,因此您可以删除 new JSONArray.

带有对象参数的 JSONArray 构造器期望它是一个集合或数组(不是 JSONArray)

试试这个:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

关于java - 在 JSON 对象中解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650171/

相关文章:

java - 仅反转字符串中的字母并保持单词的顺序相同

javascript - 使用 JSON 对象与 localStorage/sessionStorage/IndexedDB/WebSQL/等?

javascript - 如何使用 ajax 发布一些内容然后检索它?

c++ - Boost Spirit 字符解析器

java - 关于委托(delegate)-事件-模型模式中的监听器

java - 在 HashMap<String,ArrayList<Model>> 中遇到问题,(在 Android 中创建评论 View )

java - 使用 Spring Cloud 连接器访问 CloudFoundry 用户提供的服务

java - 在 JDK 8 中,Nashorn 和新的 JSON-P (javax.json) API 之间是否有计划的互操作性?

python - Python 中 bool 值 'and' 和 'or' 的运算符方法是什么?

html - 使用 mechanize 从 HTML 表中提取数据