0

Simply I have a POJO like this:

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

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

When I create the JSON object using the JsonFactory and ObjectMapper, it would be something like:

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

Now, the question is how can I generate something like the following without manual mapping.

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

Note that, I know how to do manual mapping. Also, I need to use some features like Include.NON_EMPTY.

4

1 回答 1

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"
} ] }

只需稍加努力,您就可以将示例重构为自定义序列化程序,可以按照此处记录的方式插入该序列化程序。

于 2014-04-17T22:19:14.660 回答