3
我編程導航到返回應用程序/ JSON格式的站點。我似乎無法閱讀HttpURLConnection中返回的json。我正在使用傑克遜將JSON解密到java對象中。代碼是:如何分析應用程序/ JSON對象爲String
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: [email protected]adf9; 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
它提示我downl填寫一個文件。一旦你打開該文件,它已被下載後,它包含:
{
"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"
}
我也試圖通過直接輸入流傑克遜,但它具有相同的結果失敗了。
geoLocation = (new ObjectMapper()).readValue(urlConn.getInputStream(), GeoLocation.class);
任何想法,我怎麼能檢索來自URLConn的JSON在可見字符串格式,這樣我就可以把它傳遞給Jacson?
謝謝
如果是這樣的問題,你也可以換連接的InputStream的在GZipInputStream進行解碼。 –