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!

1

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

sorry it was just a typo.
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.

1 Comment

sorry it was just a typo.
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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.