我遇到了一个听起来很容易解决的问题,但对我来说还不是很清楚。
我在此URL上从Web服务收到Json 。您会看到我有一个名为“ messages”的对象的JsonArray:
{"status":"200",
"messages":[
{"Id":"3",
"Titel":"Test",
"Bericht":"Test",
"Datum":"2014-07-10 0:45:12"},
{...}
]
}"
我让Android解析了这个接收到的上下文,但是显然数组“ messages”以某种方式转换为assoc数组:
{"status":"200",
"messages":[
{"2":
{"Id":"3",
"Titel":"Test",
"Bericht":"Test",
"Datum":"2014-07-10 0:45:12"}
},
{"3": {...}}
]
}"
这就是我接收json字符串的方式:
// appending params to url
if (params != null) {
String urlParams = "";
for(NameValuePair param : params) {
urlParams += "/" + URLEncoder.encode(param.getName(), "UTF-8") + "/";
urlParams += URLEncoder.encode(param.getValue(), "UTF-8");
}
url += urlParams.replace("+", "%20");
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity);
返回值是上面的第一个json。知道为什么会这样吗?我以为Android不会将接收到的内容解释为Json,因此我不知道该数组如何变成assoc数组。
问题来自于:EntityUtils.toString(httpEntity)
。您应该使用以下功能:
private static final String parseStringFromResponse(
final HttpResponse response) throws Exception {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
return str.toString();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句