1

当我从 url.openConnection() 的输出流生成字符串时,我的 JSON 未正确编码。例如,字符串中的引号应该有 \" 而不是 "。

预期的:

recvbuff == {"question": "What is your favorite \"color\""}

实际的:

recvbuff == {"question": "What is your favorite "color""}

代码:

String recvbuff = "";
String recv = "";

URL url = new URL("http://test.com/questions");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");

BufferedReader buffread = new BufferedReader(new InputStreamReader(con.getInputStream()));

while ((recv = buffread.readLine()) != null) {
   recvbuff += recv;
}

buffread.close();

4

1 回答 1

1

尝试用 \" 替换双引号

String result =  recvbuff .replace("\"", "\\\"");

或使用 json 对象 api:

JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "Hello \"World\"");
String payload = jsonObject.toString();
于 2021-02-17T21:03:05.583 回答