0

単純に、次のような POJO があります。

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

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

andを使用して JSON オブジェクトを作成するJsonFactoryObjectMapper、次のようになります。

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

さて、問題は、手動マッピングなしで次のようなものをどのように生成できるかです。

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

手動マッピングの方法を知っていることに注意してください。また、のようないくつかの機能を使用する必要がありますInclude.NON_EMPTY

4

1 に答える 1

1

次のように 2 段階の処理を実装できます。

まず、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 に答える