Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - How to parse a JSON and turn its values into an Array?

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();
        }
    }

As you can see, this sample code will print out the KEY of the JSONs, followed by the VALUES of the JSONS.

It would print profiles, john if the json was like this:

{'profiles':'john'}

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}]}

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.

question from:https://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values-into-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

for your example:

{'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");

this returns the array object.

Then iterating will be as follows:

    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...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...