如何使用Jackson Annotation进行映射

时间:2014-04-04 19:50:25

标签: java json jackson fasterxml

我只有这样的POJO:

@JsonInclude(value=Include.NON_EMPTY)
public class Contact {

    @JsonProperty("email")
    private String email;
    @JsonProperty("firstName")
    private String firstname;
    @JsonIgnore
    private String subscriptions[];
...
}

当我使用JsonFactoryObjectMapper创建JSON对象时,它将类似于:

{"email":"test@test.com","firstName":"testName"}

现在,问题是如何在没有手动映射的情况下生成类似下面的内容。

{"properties": [
     {"property": "email", "value": "test@test.com"},
     {"property": "firstName", "value": "testName"}
 ]}

请注意,我知道如何进行手动映射。另外,我需要使用Include.NON_EMPTY等一些功能。

1 个答案:

答案 0 :(得分:1)

您可以按如下方式实施两个步骤处理。

首先,使用ObjectMapper将bean实例转换为JsonNode实例。这保证应用所有杰克逊注释和定制。其次,您手动将JsonNode字段映射到“属性 - 对象”模型。

以下是一个例子:

public class JacksonSerializer {

public static class Contact {
    final public String email;
    final public String firstname;
    @JsonIgnore
    public String ignoreMe = "abc";

    public Contact(String email, String firstname) {
        this.email = email;
        this.firstname = firstname;
    }
}

public static class Property {
    final public String property;
    final public Object value;

    public Property(String property, Object value) {
        this.property = property;
        this.value = value;
    }
}

public static class Container {
    final public List<Property> properties;

    public Container(List<Property> properties) {
        this.properties = properties;
    }
}

public static void main(String[] args) throws JsonProcessingException {
    Contact contact = new Contact("abc@gmail.com", "John");
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.convertValue(contact, JsonNode.class);
    Iterator<String> fieldNames = node.fieldNames();
    List<Property> list = new ArrayList<>();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        list.add(new Property(fieldName, node.get(fieldName)));
    }
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Container(list)));
}

}

输出:

{ "properties" : [ {
"property" : "email",
"value" : "abc@gmail.com"
}, {
"property" : "firstname",
"value" : "John"
} ] }

只需稍加努力,您就可以将示例重新计算为自定义序列化程序,可以按照文档here进行插入。