为什么Gson会向String添加斜杠

时间:2016-11-08 04:36:47

标签: java servlets gson

我实现了一个简单的HttpServlet。 servlet接收请求并调用第三方API来获取数据,然后将数据作为响应发送回来。但是,在响应中,JSON添加了太多斜杠。

有谁知道为什么?
以下是我的代码。

public class InstitutionServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Gson gson = new Gson();

        String city = request.getParameter("city");
        String apiUrl = "https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=" + city;
        String data = getInstitutions(apiUrl);

        response.setContentType("application/json");
        PrintWriter pw = response.getWriter();
        gson.toJson(data, pw);
    }

    //Get institutions data from API url.
    private String getInstitutions(String apiUrl) {
        StringBuilder institutions = new StringBuilder();

        try {
            URL url = new URL(apiUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                institutions.append(line).append("\n");
            }

            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return institutions.toString();
    }
}

API https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=whatever的原始数据:

{
    "help": "https://inventory.data.gov/api/3/action/help_show?name=datastore_search",
    "success": true,
    "result": {
        "resource_id": "38625c3d-5388-4c16-a30f-d105432553a4",
        "q": "whatever",
        "records": [],
        "_links": {
            "start": "/api/action/datastore_search?q=whatever&resource_id=38625c3d-5388-4c16-a30f-d105432553a4",
            "next": "/api/action/datastore_search?q=whatever&offset=100&resource_id=38625c3d-5388-4c16-a30f-d105432553a4"
        }
    }
}

servlet响应中的数据http://localhost:8080/getInstitutions?city=wahtever

"{\"help\": 
  \"https://inventory.data.gov/api/3/action/help_show?name\u003ddatastore_search\", 
  \"success\": true, 
  \"result\": {
    \"resource_id\": \"38625c3d-5388-4c16-a30f-d105432553a4\", 
    \"q\": \"wahtever\", 
    \"records\": [], 
    \"_links\": {
      \"start\": \"/api/action/datastore_search?q\u003dwahtever\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\", 
      \"next\": \"/api/action/datastore_search?q\u003dwahtever\u0026offset\u003d100\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\"
    }
  }
}\n"

1 个答案:

答案 0 :(得分:1)

gson.toJson(data, pw)正在使用字符串data并将其转换为JSON,因此,为了创建有效的JSON字符串,它将转义它需要的所有字符。

为什么你需要Gson用于这种情况并不是很清楚,你应该能够直接向data写出PrintWriter,假设其他函数已经返回了JSON格式的字符串。

相关问题