如您所见,此示例代码将打印出 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 是这样的,它会打印 profiles, john:
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 并将其值转换为数组?
发布评论