如何将application / json对象解析为String

时间:2011-11-11 08:46:23

标签: json jackson urlconnection

我以编程方式导航到返回application / json格式的站点。我似乎无法读取HttpURLConnection中返回的json。我正在使用Jackson将JSON解组为java对象。代码是:

InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
    sb.append(line);
    line = br.readLine();
}
geoLocation = (new ObjectMapper()).readValue(sb.toString(), GeoLocation.class);

当我打印sb.toString()时,我会看到有趣的字符和unicodes。我应该得到一个结构良好的字符串。由此产生的异常是:

org.codehaus.jackson.JsonParseException: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@3f6dadf9; line: 1, column: 2]
    at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1291)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)

例如,如果我的网址是:

http://api.ipinfodb.com/v3/ip-city/?key=<mykeyhere>&ip=38.111.145.101&format=xml

我在浏览器窗口中获得以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <statusCode>OK</statusCode>
    <statusMessage></statusMessage>
    <ipAddress>38.111.145.101</ipAddress>
    <countryCode>US</countryCode>
    <countryName>UNITED STATES</countryName>
    <regionName>CALIFORNIA</regionName>
    <cityName>OAKLAND</cityName>
    <zipCode>94601</zipCode>
    <latitude>37.7993</latitude>
    <longitude>-122.24</longitude>
    <timeZone>-08:00</timeZone>
</Response>

但是当我做的时候

http://api.ipinfodb.com/v3/ip-city/?key=<mykeyhere>&ip=38.111.145.101&format=json

它提示我下载文件。下载后打开文件后,它包含:

{
    "statusCode" : "OK",
    "statusMessage" : "",
    "ipAddress" : "38.111.145.101",
    "countryCode" : "US",
    "countryName" : "UNITED STATES",
    "regionName" : "CALIFORNIA",
    "cityName" : "OAKLAND",
    "zipCode" : "94601",
    "latitude" : "37.7993",
    "longitude" : "-122.24",
    "timeZone" : "-08:00"
}

我也尝试将输入流直接传递给jackson,但失败的结果相同。

geoLocation = (new ObjectMapper()).readValue(urlConn.getInputStream(), GeoLocation.class);

我知道如何以可查看的字符串格式从URLConn中检索JSON,以便将其传递给Jacson吗?

谢谢

1 个答案:

答案 0 :(得分:6)

默认情况下,HttpURLConnection会将编码设置为gzip。一旦我禁用它,我就能从流中读取字符串:

urlConn.setRequestProperty("Accept-Encoding", "identity");