如何解析 JSON 并将其值转换为数组? [英] How to parse a JSON and turn its values into an Array?

查看:41
本文介绍了如何解析 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 是这样的,它会打印 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 并将其值转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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