当我从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();
发布于 2021-02-18 05:03:06
尝试将双引号替换为“
String result = recvbuff .replace("\"", "\\\"");
或者使用json对象api:
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "Hello \"World\"");
String payload = jsonObject.toString();
https://stackoverflow.com/questions/66249810
复制相似问题