简体   繁体   English

JSON + Java字符解码

[英]JSON + Java Character Decoding

My code below is using Java's URLConnection to ping a RESTful API which will return a JSON string. 我下面的代码使用Java的URLConnection对RESTful API进行ping操作,该API将返回JSON字符串。 The JSON string that I get back appears to be completely valid, but fails in both JSONLint and the final line of code below. 我返回的JSON字符串似乎完全有效,但是在JSONLint和下面的最后一行代码中均失败。

The returned JSON is: 返回的JSON是:

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

The error message is: 错误消息是:

Parse error on line 2: ...rowId": "1-12C-1494" -----------------------^ Expecting '}', ':', ',', ']' 解析第2行上的错误:... rowId“:” 1-12C-1494“ ----------------------- ^期望'}',': ',',',']'

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. 如果我从浏览器ping RESTful API并将JSON复制到JSONLint,则验证就可以了。 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. 好的,这与我从Stream到String的方式有关。 The method in the example above left a ~1000 byte gap in the middle of JSON. 上例中的方法在JSON中间留了约1000个字节的间隙。 JSONLint treated it as a whitespace character it couldn't interpret or even render. JSONLint将其视为无法解释甚至无法呈现的空白字符。

Moral of the story... don't use the method I did to go from InputStream to String. 故事的寓意...不要使用我从InputStream转到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 请参阅阅读/将InputStream转换为字符串以进行讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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