如何解析JSON并将其值转换为数组?

编程入门 行业动态 更新时间:2024-10-27 20:32:28
本文介绍了如何解析JSON并将其值转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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并将其值转换为数组?

本文发布于:2023-11-03 16:54:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   并将其   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!