从 android 中的 Json 字符串中删除反斜杠

Remove back slash from Json String in android

我需要一些帮助来从 Json 字符串中删除反斜杠。

这是我从服务器端获得的响应。

"response":"{\"time_zone\":\"\",\"session_token\":\"abcdefgHijklomopqrstuvwxyz\",\"user_login\":\"abc\",\"user_profile_img\":\"http://jhjhjhj.org/system/photos/62/medium/images.jpg?1462446436\",\"success\":\"0\",\"org_admin\":\"\",\"user_id\":\"62\",\"user_org_id\":\"101\",\"phone_mobile\":\"510-427-9639\",\"user_email\":\"abc@pdmoffice.com\"}"}

我为从这个字符串中删除反斜杠做了什么

result.replaceAll("\\","");

比之后它会给我这个不在 Json Formate 中的字符串。

{"response":"{"time_zone":"","session_token":"nskfndkjfsfsdffjsdfd","user_login":"newoff2","user_profile_img":"http://absdds.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9639","user_email":"hjhjh@pdmoffice.com"}"}

它给我解释

    org.json.JSONException: Unterminated object at character 17 of 

{"response":"{"time_zone":"","session_token":"kjshhdscncnxzcxclx","user_login":"newoff2","user_profile_img":"http://abcd.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9898","user_email":"sdgas@pdmoffice.com"}"}

如何使用正确的 Json Formate 删除这个反斜杠?

提前致谢

命令

result.replaceAll("\","");

是正确的,如果您尝试使用在线 json 格式化程序 (https://jsonformatter.curiousconcept.com/) 显示服务器响应,您可以清楚地看到字符串格式不正确。 "response" 后面的双引号和末尾的双引号不是必需的。

更新时间:2019 年 8 月 通过自动省略反斜杠,使用 google 的 Gson 解析为 Json:

JAVA 代码:

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = jsonParser.parse("your jsonString with backslash").getAsJsonObject();

科特林代码:

    val jsonParser = JsonParser()
    val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject

从 JSON 字符串中删除反斜杠的替代方法。

s = Your String with Back Slash

用于将 String 转换为 JSONObject:

JSONObject jsonObject = new JSONObject(s);

用于将字符串转换为JSON数组:

JSONArray jsonArray = new JSONArray(s);

你可以试试这个,它会很好用

String jsonStr4 = jsonStr3.replaceAll("\"", "");