views:

349

answers:

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

+1  A: 

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONArray the_json_array = the_json.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.

The Elite Gentleman