【问题标题】:How to use Jackson Annotation to do a mapping如何使用 Jackson Annotation 进行映射
【发布时间】:2014-04-04 19:50:24
【问题描述】:

我有一个像这样的 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

【问题讨论】:

  • 什么会消耗生成的 JSON?这似乎是一种非常复杂的格式。

标签: java json jackson fasterxml


【解决方案1】:

您可以实现如下两步处理。

首先,您使用 ObjectMapper 将 bean 实例转换为 JsonNode 实例。这保证应用所有 Jackson 注释和自定义。其次,您手动将 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 插入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多