在JSON对象中解析JSON数组 [英] Parsing JSON Array within JSON Object

查看:375
本文介绍了在JSON对象中解析JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some JSON with the following structure:

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

我将此JSON字符串命名为 mainJSON 。我正在尝试使用以下Java代码访问元素name和age:

I have named this JSON string as mainJSON. I'm trying to access the elements "name" and "age" with the following Java code:

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行显示以下异常:

I'm being shown the following exception for line number 2:

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

请指导我在哪里弄错了以及如何纠正这个问题。

Please guide me as to where I'm making the mistake and how to rectify this.

推荐答案

mainJSON.getJSONArray(source)返回 JSONArray ,因此你可以删除 new JSONArray。

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

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

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

试试这个:

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

这篇关于在JSON对象中解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆