问题描述
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();
}
}
如您所见,此示例代码将打印出来JSON的 KEY ,然后是JSONS的 VALUES 。
As you can see, this sample code will print out the KEY of the JSONs, followed by the VALUES of the JSONS.
它会打印个人资料,约翰如果json是这样的:
It would print profiles, john if the json was like this:
{'profiles':'john'}
这很酷。这很好,因为我可以使用这些变量。但是,如果JSON是这样的话:
That's cool. That's fine, as I can work with those variables. However, what if the JSON was like this:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
在这种情况下,整个值将是数组。基本上,我只想抓住那个数组(在这种情况下是值)......并将其转换为JAVA可以使用的实际数组。我怎样才能做到这一点?谢谢。
In this case, the entire value would be the array. Basically, I just want to grab that array (which is the "value" in this case)...and turn it into an actual array that JAVA could use. How can I do that? Thanks.
推荐答案
为您的例子:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
你必须做一些这样的事情:
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
这将返回数组对象。
然后迭代如下:
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...
你必须确定是否数据是一个数组(只需检查 charAt(0)
以 [
字符)开头。
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
希望这有帮助。
这篇关于如何解析JSON并将其值转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!