java JSON 自动添加反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43161385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON adding backslash automatically
提问by Aishwarya
I am trying to convert a java object to json using Gson. But when i tried printing it out.I got this JSON
我正在尝试使用 Gson 将 java 对象转换为 json。但是当我尝试打印出来时,我得到了这个 JSON
{"user":"{\"email\":\"[email protected]\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}
{"user":"{\"email\":\"[email protected]\",\"lastName\":\"Las\",\"name\":\"amy\",\"password \":\"qwe123\",\"电话\":\"8901245244\"}"}
I tried
我试过
s.replace("\\"", "\"") but neither it helps nor its a good approach.
s.replace("\\"", "\"") 但它既没有帮助,也不是一个好方法。
Further I have gone through various links but answers are ambiguous.
此外,我浏览了各种链接,但答案不明确。
This is my User class toString method
这是我的用户类 toString 方法
public class User implements Serializable
{ ...
@Override
public String toString()
{ return "User{" +
"first_name:" + name+
", last_name:" + lastName+
", mobile:" + phone+
", email:" + email+
", password:" + password+
"}";
}
I guess its not even calling this toString method.
我想它甚至没有调用这个 toString 方法。
and here is how am I converting to JSON
这是我如何转换为 JSON
User u=new User(name,lastName,email,phone,password);
Gson userGson=new GsonBuilder().create();
String jo=userGson.toJson(u);
JSONObject params=new JSONObject();
params.put("user",jo);
Log.e("in register",params.toString());
Any help is appreciated.
任何帮助表示赞赏。
回答by Femi
You've already converted it to a JSON string, then you stick that into a JSON object which automatically escapes the JSON string. Try something like this:
您已经将其转换为 JSON 字符串,然后将其粘贴到 JSON 对象中,该对象会自动转义 JSON 字符串。尝试这样的事情:
User u=new User(name,lastName,email,phone,password);
Gson userGson=new GsonBuilder().create();
JSONObject params = new JSONObject();
params.put("user",user);
Log.e("in register", userGson.toJson(params));
回答by OneCricketeer
params.toString()
is a string representation of the JSON, not a User object.
params.toString()
是 JSON 的字符串表示形式,而不是 User 对象。
I tried s.replace("\"", "\"")
我试过 s.replace("\"", "\"")
You didn't need to do that... Java is showing the string with escape characters. If you see the escape characters, then you've converted an existing JSON string into another JSON object, and string-ed it again.
您不需要这样做... Java 显示带有转义字符的字符串。如果您看到转义字符,那么您已将现有的 JSON 字符串转换为另一个 JSON 对象,并再次对其进行字符串编辑。
String jo=userGson.toJson(u);
Why are you not logging this instead?
你为什么不记录这个呢?
I guess its not even calling this toString method
我想它甚至没有调用这个 toString 方法
Well, you never printed a User object
好吧,您从未打印过 User 对象