Reputation: 1087
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\":\"[email protected]\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}
I tried
s.replace("\\"", "\"") but neither it helps nor its a good approach.
Further I have gone through various links but answers are ambiguous.
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+
"}";
}
I guess its not even calling this toString method.
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());
Any help is appreciated.
Upvotes: 1
Views: 24153
Reputation: 191733
params.toString()
is a string representation of the JSON, not a User object.
I tried 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.
String jo=userGson.toJson(u);
Why are you not logging this instead?
I guess its not even calling this toString method
Well, you never printed a User object
Upvotes: 1
Reputation: 64700
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));
Upvotes: 3