【发布时间】:2016-10-10 08:31:11
【问题描述】:
我正在开发一个服务器-客户端应用程序。对于部分请求,我需要在Server端生成一段Json String并发送给Client。根据服务器日志,在服务器端正确生成了 Json 字符串。但是在Android客户端,String被改变了,无法解析为正确的Json String。
这里有一些相关代码。
在服务器端生成 Json 字符串:
@RequestMapping(value="/resourceList/{actType}/{type}/{id}")
@ResponseBody public Object personList(@PathVariable int actType, @PathVariable int type, @PathVariable int id){
ArrayList<ItemBase> list = new ArrayList();
......
return new ArrayList();
}
这会生成以下 Json 代码:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"shark point","userID":0,"status":"normal","rank":0.0,"id":2,"timestamp":1471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,"type":64}]
并在安卓客户端接收:
......
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buffer = new byte[256];
int len = 0;
StringBuilder responseBuilder = new StringBuilder();
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, "utf-8");
responseBuilder.append(str);
}
String response = responseBuilder.toString().trim();
响应变量被写入值:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,""type":64}]":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"
无法正确解析为 Json String 且有明显错误。
除了这个之外,大多数向客户端请求返回 Json 字符串的方法都可以正常工作。但是这种方法的实现几乎与那些正常工作的方法完全相同。因此,我根本不知道这是怎么发生的。谁有任何线索请帮忙。
【问题讨论】:
-
如果
len小于buffer大小怎么办? -
这就是为什么我必须调用 String.trim() 方法。
-
做一些研究....stackoverflow.com/questions/309424/…