Spring-将JSON字符串转换为JSON对象

时间:2019-01-08 10:25:32

标签: json rest spring-boot

我的user表存储如下:

|---------------------|------------------|-------------------------------------------------------------|
|      id             |     name         |    address                       
|---------------------|------------------|-------------------------------------------------------------|
|      1              |     ken          | {"street":"Street 1","city":"City1", "country":"USA"}       |     
|---------------------|------------------|-------------------------------------------------------------|

我的POJO:

public class User{
   private int id;
   private String name;
   private String address;
    //setters and getters
}

在我的RESTful服务中,我希望在调用API时使用以下JSON作为响应:

{
   "id": 1,
   "name": "ken",
   "address":{
        "street":"Street 1",
        "city":"City1", 
        "country":"USA"
   }
}

我可以通过将POJO中的address更改为地址对象,然后将字符串映射到地址对象来实现。

但是还有其他方法可以将我的地址保留为POJO中的字符串,然后将其呈现为JSON吗?

1 个答案:

答案 0 :(得分:3)

您可以在财产上使用@JsonSerialize

@JsonSerialize(using = CustomeSerializer.class)
private String address;


public class CustomSerializer extends StdSerializer<String>{
    public CustomSerializer(){
        this(null);
    }
    public CustomSerializer(Class<String> t) {
        super(t);
    }

    @Override
    public void serialize(String address, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeObject(new ObjectMapper().readTree(address));
    }
}