26
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.

5
  • 2
    this is valid json see jsonlint.com maybe it is your code? Feb 27, 2014 at 7:42
  • This given json lik is correct..your code which you tried and also please log cat Feb 27, 2014 at 7:52
  • The bug is somewhere in your code; it looks like you are trying to parse a JSON value which is not an object using JSONObject. As an alternative, use a better JSON library, such as Jackson.
    – fge
    Feb 27, 2014 at 7:53
  • 1
    Try printing str.charAt(0) and see what the first char is. It could be a [ in that case its a json array. Or you might have a hidden char of some sort.
    – ug_
    Feb 27, 2014 at 8:00
  • @ns47731, he has posted a link to the JSON he's parsing and there is no [. str.charAt(0) is still a good debug step, though.
    – OrhanC1
    Feb 27, 2014 at 9:18

14 Answers 14

19

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);
0
16

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.

0
13

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); 
    .....   
}
1
  • 33
    Or you may use JSONArray jsonArray = new JSONArray(output);
    – Tim Autin
    Jan 22, 2015 at 22:00
4

I had the same, there was an empty new line character at the beginning. That solved it:

int i = result.indexOf("{");
result = result.substring(i);
JSONObject json = new JSONObject(result.trim()); 
System.out.println(json.toString(4));  
1
  • Works like charm
    – ucMedia
    Sep 20, 2020 at 12:27
2

I had the same issue because of the wrong order of the code statements. Maintain the below order to resolve the issue. All get methods statements first and later httpClient methods.

      HttpClient httpClient = new HttpClient();
get = new GetMethod(instanceUrl+usersEndPointUri);
get.setRequestHeader("Content-Type", "application/json");
get.setRequestHeader("Accept", "application/json");

httpClient.getParams().setParameter("http.protocol.single-cookie-header", true);
httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.executeMethod(get);
2

In my case the json file encoding was a problem

I was generating JSON file in vb .net with following: My.Computer.FileSystem.WriteAllText("newComponent.json", json.Trim, False)

And I tried all suggestions in this post but none helped.

Eventually in Notepad++ noticed that the file created was in UTF-8-BOM

Not sure how it picked up that encoding but after I switched the encoding to UTF-8, it resolved with no other changes.

Hope this helps someone.

2

I had the same error and struggled to fix it, then answer above by Nagaraja JB helped me to fix it. In my case:

Was before: JSONObject response_json = new JSONObject(response_data);

Changed it to: JSONArray response_json = new JSONArray(response_data);

This fixed it.

1

I had similar issue due to a small mistake, when i was trying to convert a List to json. If a List is converted to json it will return JSONArray not JSONObject.

1

in my case my arraylist trhows me that error with the JSONObject , but i fin this solution for my array of String objects

List<String> listStrings= new ArrayList<String>();
String json = new Gson().toJson(listStrings);
return json;

Works like charm with angular Gson version 2.8.5

0
1

The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.

1

Response:

 [
        {
          "idGear": "1",
          "name": "Nosilec za kolesa",
          "year": "2005",
          "price": "777.0"
        }, {
          "idGear": "2",
          "name": "Stresni nosilci",
          "year": "1983",
          "price": "40.0"
        }
      ]

Assuming your response is somewhat similar to this one. You can use JSONArray instead of JSONObject and then depending on your response either you can iterate it or get the element at 0th index.

JSONArray json_arr = new JSONArray(response_string);
JSONObject single_response = json_arr.get(0); //for single element
for(int i=0;i<json_arr.length();i++){         // OR iterate
    JSONObject tmp = json_arr.get(i);
} 
1

This problem does not happen in JSON. You need to open the URL connection using HttpURLConnection.

    HttpURLConnection connection = null;
    try{            
        URL url = new URL("http://www.json-generator.com/j/cglqaRcMSW?indent=4");
        connection =  (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type","application/json");
        connection.setRequestProperty("Accept","application/json");
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.connect();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer stringBuffer = new StringBuffer();
        String output;
        while((output = bufferedReader.readLine()) != null ){
            stringBuffer.append(output);
        }
        bufferedReader.close();
        System.out.println(stringBuffer.toString());
    }
    catch(Exception e){
        System.out.println(e);
    }
    finally{
        if (connection != null) {
        try {
            connection.disconnect();
        }catch (Exception ex) {
            System.out.println("Error");
        }
     }
0

In my cases it was " "(double quotes) issue when I replaced it with ' '(single quotes) it worked for me. Please check sample after data.

This may work for you.

enter image description here

-1

Actually,,i found a simple answer,, Jst adding the object to String Builder instead of String worked ;)

StringBuilder jsonString= new StringBuilder.append("http://www.json-.com/j/cglqaRcMSW?=4");    
JSON json= new JSON(jsonString.toString);
3
  • 1
    I'm pretty sure this is incorrect. Can you explain please how exactly did this fix your problem? It's still not opening a connection to retrieve the JSON from the server and it's not a valid JSON, it's a URL. Moreover, new StringBuilder.append is not valid Java syntax. As you unaccepted my answer I want to know why this is better, thanks. May 27, 2014 at 11:21
  • 1
    The code here is incorrect, why not use Assaf's answer?
    – Itaypk
    May 27, 2014 at 11:25
  • 1
    How exactly does using a string builder solve the problem? You are still passing a URL and trying to create a JSON object from it, which is incorrect.
    – Léo Natan
    May 29, 2014 at 9:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.