Parse JSON without key

advertisements

My basic JSON data structure is this:

[
  {
    "data1":"contents of data1",
    "data2":"contents of data 2"
  },
  {
    "data1":"contents of data1",
    "data2":"contents of data 2"
  }
]

I tried using JSONArray myJson = new JSONArray(json);

but it gives me:

org.json.JSONException: Not a primitive array: class org.json.JSONObject

I am retrieving the JSON through:

JSONParser jParser = new JSONParser();

// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);

And convert it to JSONArray using JSONArray myJson = new JSONArray(json);

Thanks!


Iterate your json without key as follows

try {
    JSONArray jsonArray = new JSONArray("[{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"},{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"}]");

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        Iterator<?> keys = jsonObject.keys();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));
        }
    }

} catch (JSONException e) {
    e.printStackTrace();
}