在POJO中的单个字段上映射内部对象值(JSON对象)

时间:2016-02-19 14:27:37

标签: java json jackson mapping automapper

我正在使用Jackson在java POJO上进行json映射。我想要的是将JSON的内部字段映射到我的父Java POJO,并且需要通过任何注释询问是否可能?我的JSON如下

{
        "email": "xyz@abc.com",
        "name": {
            "forenames": "John",
            "surname": "Doe"
    }
}        

和POJO是:

 public class CustomerVo {

        @JsonProperty("last4")
        private String emailAddress; 

        /*is there any annotation available that I can use to concat
        fornames and surname in 'customeName' ?? */
        private String customerName; 

    }

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

有一种称为@JsonCreator的东西,据说

  

@JsonCreator:用于指示构造函数或注释的注释   应使用静态工厂方法来创建值实例   在反序列化期间。

示例here 3.1。点。 Jackson的文档。

答案 1 :(得分:0)

首先,您可以编写一个类CustomerName,它将序列化您的属性。如果您不想实现单独的类,则需要自定义JsonDeserializerJsonSerializer(顺便说一句:代码不仅仅是编写CustomerName类)。例如,

public class CustomerNameJsonSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String customerName, JsonGenerator jg, SerializerProvider sp) throws IOException {
        jg.writeStartObject();

        jg.writeFieldName("forenames");
        jg.writeString(/* extract your forenames from customerName */);

        jg.writeFieldName("surname");
        jg.writeString(/* extract your surname from customerName */);

        jg.writeEndObject();
    }

}

public class CustomerNameJsonDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
        TreeNode tree = jp.readValueAsTree();
        TextNode forenames = (TextNode) tree.path("forenames");
        TextNode surname = (TextNode) tree.path("surname");

        return forenames.asText() + ":" + surname.asText();
    }

}

public class CustomerVo {

    @JsonProperty("last4")
    private String emailAddress; 

    @JsonProperty("name")
    @JsonSerialize(using = CustomerNameJsonSerializer.class)
    @JsonDeserialize(using = CustomerNameJsonDeserializer.class)
    private String customerName; 

}