Denny Mathew
Denny Mathew

Reputation: 853

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

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.

Upvotes: 26

Views: 249821

Answers (14)

Ajay
Ajay

Reputation: 740

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

Upvotes: 0

Navin Christopher
Navin Christopher

Reputation: 21

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

Upvotes: 1

Damnik Jain
Damnik Jain

Reputation: 434

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

Upvotes: 2

T J
T J

Reputation: 11

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

Upvotes: 1

Raymond
Raymond

Reputation: 470

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

Upvotes: 21

sonu1986
sonu1986

Reputation: 231

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.

Upvotes: 2

Dinesh
Dinesh

Reputation: 41

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.

Upvotes: 2

Andres Navarro
Andres Navarro

Reputation: 137

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

Upvotes: 1

Nagaraja JB
Nagaraja JB

Reputation: 753

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.

Upvotes: 1

AKB
AKB

Reputation: 5938

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

Upvotes: 13

Denny Mathew
Denny Mathew

Reputation: 853

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

Upvotes: -1

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

Upvotes: 3

palossyl
palossyl

Reputation: 51

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

Upvotes: 5

Assaf Gamliel
Assaf Gamliel

Reputation: 12015

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.

Upvotes: 17

Related Questions