Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

Tags:

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";

JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("get");
Object level = getSth.get("2");

System.out.println(level);

I referred many solutions for parsing this link, still getting the same error in question. Can any give me a simple solution for parsing it.

like image 586
Denny Mathew Avatar asked Feb 27 '14 07:02

Denny Mathew


3 Answers

Your problem is that String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4"; is not JSON.
What you want to do is open an HTTP connection to "http://www.json-generator.com/j/cglqaRcMSW?indent=4" and parse the JSON response.

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!

Will not open a connection to the site and retrieve the content.

like image 197
Assaf Gamliel Avatar answered Nov 11 '22 08:11

Assaf Gamliel


While the json begins with "[" and ends with "]" that means this is the Json Array, use JSONArray instead:

JSONArray jsonArray = new JSONArray(JSON);

And then you can map it with the List Test Object if you need:

ObjectMapper mapper = new ObjectMapper();
List<TestExample> listTest = mapper.readValue(String.valueOf(jsonArray), List.class);
like image 21
Raymond Avatar answered Nov 11 '22 07:11

Raymond


I had same issue. My Json response from the server was having [, and, ]:

[{"DATE_HIRED":852344800000,"FRNG_SUB_ACCT":0,"MOVING_EXP":0,"CURRENCY_CODE":"CAD  ","PIN":"          ","EST_REMUN":0,"HM_DIST_CO":1,"SICK_PAY":0,"STAND_AMT":0,"BSI_GROUP":"           ","LAST_DED_SEQ":36}]

http://jsonlint.com/ says valid json. you can copy and verify it.

I have fixed with below code as temporary solution:

BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String result ="";
String output = null;
while ((result = br.readLine()) != null) {
    output = result.replace("[", "").replace("]", "");
    JSONObject jsonObject = new JSONObject(output); 
    JSONArray jsonArray = new JSONArray(output); 
    .....   
}
like image 36
AKB Avatar answered Nov 11 '22 08:11

AKB