JSON自动添加反斜杠 [英] JSON adding backslash automatically
问题描述
我正在尝试使用Gson将Java对象转换为json.但是当我尝试打印出来时,我得到了这个JSON
I am trying to convert a java object to json using Gson. But when i tried printing it out.I got this JSON
{"user":"{\" email \:\" abc@gmail.com \,\" lastName \:\" Las \,\" name \:\" amy \, \密码\":\"qwe123 \",\电话\":\"8901245244 \"}}
{"user":"{\"email\":\"abc@gmail.com\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}
我尝试过
s.replace("\\"," \") 但它既无济于事,也不是一个好方法.
s.replace("\\"", "\"") but neither it helps nor its a good approach.
我还经历了各种链接,但答案却模棱两可.
Further I have gone through various links but answers are ambiguous.
这是我的User类toString方法
This is my User class toString method
public class User implements Serializable
{ ...
@Override
public String toString()
{ return "User{" +
"first_name:" + name+
", last_name:" + lastName+
", mobile:" + phone+
", email:" + email+
", password:" + password+
"}";
}
我想它甚至都没有调用此toString方法.
I guess its not even calling this toString method.
这是我如何转换为JSON
and here is how am I converting to 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());
感谢您的帮助.
推荐答案
您已经将其转换为JSON字符串,然后将其粘贴到JSON对象中,该对象会自动转义JSON字符串.尝试这样的事情:
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:
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));
这篇关于JSON自动添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!