JSONParser returns Unexpected character () at position 0

All Pereira picture All Pereira · Dec 14, 2017 · Viewed 7.9k times · Source

I'm with problem to parse a JSON. Always that I try do it, the follow was result is returned: Unexpected character () at position 0.

public Object execute(HttpRequestBase request){
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = null;
    Object object = null;

    try {
        response = client.execute(request);
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader((is)));
        StringBuilder builder = new StringBuilder();
        String output;

        while ((output = br.readLine()) != null) {
            builder.append(output).append("\n");    
        }

         if (response.getStatusLine().getStatusCode() == 200) { 
            object = new JSONParser().parse(builder.toString());
            client.getConnectionManager().shutdown();
        } else {
             LOG.log(Level.SEVERE, builder.toString());
             throw new RuntimeException(builder.toString());
         }

    } catch (IOException | ParseException ex) {
        LOG.log(Level.SEVERE, ex.toString());
    } finally {

    }

    return object;
}

PS:

  1. My response returns a JSON well formatted;
  2. The problem happens when this piece of code is running object = new JSONParser().parse(builder.toString());

The is part o my JSON file:

    [
   {
      "id":2115,
      "identificacao":"17\/2454634-6",
      "ultima_atualizacao":null
   },
   {
      "id":2251,
      "identificacao":"17\/3052383-2",
      "ultima_atualizacao":"2017-11-21"
   },
   {
      "id":2258,
      "identificacao":"17\/3070024-6",
      "ultima_atualizacao":null
   },
   {
      "id":2257,
      "identificacao":"17\/3070453-5",
      "ultima_atualizacao":null
   }
]

Answer

Aleh Maksimovich picture Aleh Maksimovich · Dec 14, 2017

Most probably your content has some unprinted special character at beginning. For UTF-8 encoded data this may be a BOM.

Please post start of you content as byte[].