gpt4 book ai didi

java - Gson为什么要给String加斜杠

转载 作者:行者123 更新时间:2023-12-01 09:16:57 24 4
gpt4 key购买 nike

我实现了一个简单的 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"

最佳答案

gson.toJson(data, pw) 正在获取字符串 data 并将其转换为 JSON,因此要做到这一点,它将转义所需的所有字符为了创建一个有效的 JSON 字符串。

目前还不清楚为什么在这种情况下需要 Gson,您应该能够直接将 data 写入 PrintWriter 假设其他函数已经返回JSON 格式的字符串。

关于java - Gson为什么要给String加斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com