ricardoramos
ricardoramos

Reputation: 946

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

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 ?

Upvotes: 3

Views: 21039

Answers (1)

Srikanth Balaji
Srikanth Balaji

Reputation: 2718

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");
            }
        }

Upvotes: 3

Related Questions