如何使用gson在其中已经包含json的某些String字段的情况下将pojo转换为json?

时间:2018-10-04 14:56:35

标签: java json gson pojo

我有一个pojo,如下所示。我有一个toString方法,负责将其转换为json数据。如您所见,我在该toString方法中使用gson。

// removed setters for brevity
public class User {

    private String name, email, password;

    // This information field is already a json as mentioned below
    private String information;

    public User(String name, String email, String password, String information) {
        super();
        this.name = name;
        this.email = email;
        this.password = password;
        this.information = information;
    }

    @Override
    public String toString() {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        return gson.toJson(this);
    }

问题是在所有这些字段中,我的information字段已经是一个json字符串。在我的主程序中,我正在像这样填充该User对象。

// filled it with random info, but I will get this from someplace else
String info = "{  \r\n" + 
        "   \"street_address\":{  \r\n" + 
        "      \"type\":\"string\"\r\n" + 
        "   },\r\n" + 
        "   \"city\":{  \r\n" + 
        "      \"type\":\"string\"\r\n" + 
        "   },\r\n" + 
        "   \"state\":{  \r\n" + 
        "      \"type\":\"string\"\r\n" + 
        "   }\r\n" + 
        "}";

User user = new User("John", "Doe", "password", info);

return user.toString();

这是我得到的输出。

{
  "name": "John",
  "email": "Doe",
  "password": "password",
  "information": "{\r\n    \"street_address\": { \"type\": \"string\" },\r\n    \"city\":           { \"type\": \"string\" },\r\n    \"state\":          { \"type\": \"string\" }\r\n}"
}

我想要的是information的最后一个also字段的格式正确,这就是我期望的本示例。

{  
   "name":"John",
   "email":"Doe",
   "password":"password",
   "information":{  
      "street_address":{  
         "type":"string"
      },
      "city":{  
         "type":"string"
      },
      "state":{  
         "type":"string"
      }
   }
}

0 个答案:

没有答案