简体   繁体   中英

JSON + Java Character Decoding

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM