0

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!

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Jayson Tamayo
  • 2,741
  • 3
  • 49
  • 76
  • Possible duplicate of [Get JSONArray without array name?](http://stackoverflow.com/questions/10164741/get-jsonarray-without-array-name) – marmor Sep 29 '16 at 08:48

3 Answers3

1

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();
}
Nikhil
  • 3,711
  • 8
  • 32
  • 43
0

The reason of that error might be invalid json.

This is how your data2 key - value pair is

"data2":contents of data 2"

Put the quotes " before contents and use this

"data2":"contents of data 2"

Change all occurences of this error and it should work. Do let me know if it changes anything for you.

Nishant Dubey
  • 2,802
  • 1
  • 13
  • 18
0

In python, If u have json data as

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

you can access it using: print "data1:",data[0]["data1"]