public static void parseProfilesJson(String the_json){
try {
JSONObject myjson = new JSONObject(the_json);
JSONArray nameArray = myjson.names();
JSONArray valArray = myjson.toJSONArray(nameArray);
for(int i=0;i<valArray.length();i++)
{
String p = nameArray.getString(i) + "," + ValArray.getString(i);
Log.i("p",p);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,此示例代码将打印出JSON 的KEY,然后是JSONS的VALUES.
它将打印配置文件,如果json是这样的约翰:
{'profiles':'john'}
Run Code Online (Sandbox Code Playgroud)
这很酷.那很好,因为我可以使用这些变量.但是,如果JSON是这样的:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,整个值将是数组.基本上,我只想抓住那个数组(在这种情况下是"值")......然后把它变成JAVA可以使用的实际数组.我怎样才能做到这一点?谢谢.
Buh*_*ndi 57
为你的例子:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
Run Code Online (Sandbox Code Playgroud)
你将不得不做这样的事情:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
Run Code Online (Sandbox Code Playgroud)
这将返回数组对象.
然后迭代将如下:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
Run Code Online (Sandbox Code Playgroud)
您必须确定数据是否是数组(只需检查charAt(0)以[字符开头).
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
138463 次 |
| 最近记录: |