客户端在服务器端

时间:2016-10-10 08:31:11

标签: java android json spring

我正在研究服务器客户端应用程序。对于部分请求,我需要在服务器端生成一段Json String并将其发送给Client。根据服务器日志,在服务器端正确生成了Json String。但是在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}]

在Android客户端上接收它:

......
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字符串并显示错误。

将Json String返回给客户端请求的大多数方法都可以正常工作,除了这个。但是这种方法的实现几乎完全相同。因此我根本不知道这是怎么发生的。任何人都有任何提示请帮助。

1 个答案:

答案 0 :(得分:0)

你正在以错误的方式构建String

请改为尝试:

    // …

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(request);
        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedInputStream bis = new BufferedInputStream(in);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        int result = bis.read();
        while(result != -1) {
            buf.write((byte) result);
            result = bis.read();
        }

        String response = buf.toString();

    // …