3

Iam parsing a json using org.json in java . My json list like:

[ {
"id": "f187b01b145c4171b66d4a2ecabb8f44"
},
{
"id": "a5e66b7462e24924a03e89f0619a2398"
},
{
"id": "2fb3627360db4ab78a0b3f27527b1983"
} ]

I fetch data from the java code :

JSONObject json = new JSONObject(response.getEntity(String.class));                                 
Jobs[] obj = new Gson().fromJson(json.toString(), Jobs[].class);
System.out.println(obj.toString());

But it gives an exception :

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.<init>(JSONObject.java:197)
at org.json.JSONObject.<init>(JSONObject.java:324)
at br.usp.icmc.teste.ConnectionRestClient.getSaucelabsGetJobs(ConnectionRestClient.java:80)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)

why it did not recognized as JSONArray ? Where am I wrong ?

Danielson
  • 2,605
  • 2
  • 28
  • 51
ricardoramos
  • 891
  • 3
  • 18
  • 35
  • 4
    You do not have an `JSONObject`. You have an `JSONArray` – Jens Jun 25 '15 at 12:51
  • It's a `JSONArray`, and not a `JSONObject`. Create an object of `JSONArray` from the response and than iterate through it to fetch the `JSONObject`. – Prerak Sola Jun 25 '15 at 12:51
  • Use the solution posted in http://stackoverflow.com/questions/9817315/how-to-check-whether-the-given-object-is-object-or-array-in-json-string to test types and handle it appropriately – Tschallacka Jun 25 '15 at 13:18
  • Thank you for explanation Danielson, It worked perfectly. – ricardoramos Jun 25 '15 at 16:57

1 Answers1

3
U can try with below code. There are many ways to do it, below is one of the way


JSONArray jsonArray = new JSONArray(response.getEntity(String.class));
        for(int i =0; i< jsonArray.length(); i++){
            if(jsonArray.get(i) instanceof JSONObject){
                JSONObject jsnObj = (JSONObject)jsonArray.get(i);
                String finalValue = (String)jsnObj.get("id");
            }
        }
Srikanth Balaji
  • 2,638
  • 4
  • 18
  • 31