Reputation: 2811
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!
Upvotes: 0
Views: 4833
Reputation: 3711
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();
}
Upvotes: 1
Reputation: 175
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"]
Upvotes: 0
Reputation: 2872
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.
Upvotes: 0