JSON adding backslash automatically

前端 未结 2 1042
梦谈多话
梦谈多话 2021-01-27 16:53

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

相关标签:
2条回答
  • 2021-01-27 17:19

    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

    0 讨论(0)
  • 2021-01-27 17:23

    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));
    
    0 讨论(0)
提交回复
热议问题