1

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.

0

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

If I simply output params its giving the same JSON as required and this userGson.toJson(params) is adding nameVAluPAirs like this : {"nameValuePairs":"user":"email":"[email protected]","lastName":"Lad","name":"ad","password":"1234567890","phone":"1234567890"}}}
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.