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

Mapping of inner object values (JSON object) on single field in POJO

我正在使用 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; 

    }

提前感谢您的帮助。

有个东西叫@JsonCreator,据说

@JsonCreator: annotation used for indicating that a constructor or static factory method should be used for creating value instances during deserialization.

例子here 3.1. point. Documentation for Jackson.

首先,您可以编写一个 class CustomerName 来序列化您的 属性。如果您不想实现单独的 class,您需要自定义 JsonDeserializerJsonSerializer(顺便说一句:比编写 CustomerName class).例如,

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; 

}