spring接口输出json字符串

直接用@ResponseBody然后return json字符串,在客户端调用返回的字符串转json的时候,一直各种错误无法转换。

包括缺少{开头 或者需要: 或者string无法转换json 等等。

后来把return json字符串改成用response输出,就正常转换了,原因还是不太明了,猜测是有隐藏的字节导致格式问题。

所以以后尽量用下面的方式输出json字符串:

   @RequestMapping(value = "/get", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public void api(HttpServletRequest request, HttpServletResponse response) {
      PrintWriter out = null;
        String jsondb = "";
        try {
            out = response.getWriter();
            response.setContentType("application/json;charset=utf-8");
       //这里处理业务,返回把返回的json字符串赋值给jsondb
//比如:jsondb = json字符串; 
//如果有错误或验证不通过,输出错误的json字符串,然后:return      }
catch (Exception e) { jsondb = 错误的json信息; }finally{ if (null != out) { if (StringUtil.isNotBlank(jsondb)) { try { out.print(jsondb); } catch (Exception e) { } } out.flush(); out.close(); } }   }

然后客户端转换(com.alibaba.fastjson):

JSONObject jsonObject = JSONObject.parseObject(pullInfo);

posted @ 2018-03-13 16:44  稚语希听  阅读(1055)  评论(0)    收藏  举报