0

My code below is using Java's URLConnection to ping a RESTful API which will return a JSON string. The JSON string that I get back appears to be completely valid, but fails in both JSONLint and the final line of code below.

The returned JSON is:

{ "rowId": "1-12C-1494" }

The error message is:

Parse error on line 2: ...rowId": "1-12C-1494" -----------------------^ Expecting '}', ':', ',', ']'

The code is:

StringBuilder responseBuilder = new StringBuilder();

URLConnection connection = url.openConnection();
InputStream cin = connection.getInputStream();
int bytesRead = -1;
byte[] buffer = new byte[1024];

while ((bytesRead = cin.read(buffer)) >= 0) {
    responseBuilder.append(new String(buffer, "UTF-8"));
}

String response = responseBuilder.toString();

JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();

If I ping the RESTful API from a browser and copy the JSON there into JSONLint it validates just fine. The best I can tell this some kind of character/whitespace encoding issue. Has anyone else run into it and have any guidance? Thanks!

1 Answer 1

1

Okay so it had to do with how I was going from Stream to String. The method in the example above left a ~1000 byte gap in the middle of JSON. JSONLint treated it as a whitespace character it couldn't interpret or even render.

Moral of the story... don't use the method I did to go from InputStream to String. This works much better:

InputStream cin = connection.getInputStream();

java.util.Scanner s = new java.util.Scanner(cin).useDelimiter("\\A");
(StringBuilder)responseBuilder.append(s.hasNext() ? s.next() : "");

See Read/convert an InputStream to a String for discussion

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.