Json Adding Backslash Automatically

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\":\"\",\"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

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));
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest