Jackson如何处理映射冲突?

问题描述 投票:1回答:1

我有一个以下类,其属性“键”映射到2个不同的JSON字段

public class A {

    @JsonAlias("Key")
    private String key;

    @JsonProperty("NewKey")
    private void unpackNewKey(Map<String, String> NewKey) {
        key = NewKey.get("value");
    }
}

这里是要反序列化的JSON。

{
    "NewKey": {
        "value": "newkey",
    },
    "Key": "key"
}

如果我将上述json反序列化为A.class

ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue(json, A.class)

a.key的值是多少?是newkey还是key?试图了解杰克逊如何处理冲突。我可以指定订单吗?例如,如果json中同时存在keyNewKey,如果我希望Key始终映射到NewKey,该怎么办?

java json jackson json-deserialization jackson2
1个回答
0
投票

在您的示例中,使用@JsonAlias("Key")@JsonProperty("NewKey")的顺序取决于key-value有效负载中JSON对的顺序。如果要始终使用NewKey键优先级进行反序列化,则需要在自定义JSON Deserialiser或构造函数中实现。您可以在下面找到一个简单的示例:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue("{}", A.class));
        System.out.println(mapper.readValue("{\"Key\": \"key\"}", A.class));
        System.out.println(mapper.readValue("{\"NewKey\": {\"value\": \"newkey\"}}", A.class));
        System.out.println(mapper.readValue("{\"Key\": \"key\", \"NewKey\": {\"value\": \"newkey\"}}", A.class));
        System.out.println(mapper.readValue("{\"NewKey\": {\"value\": \"newkey\"}, \"Key\": \"key\"}", A.class));
    }
}

class A {

    private String key;

    @JsonCreator
    public A(Map<String, Object> json) {
        final String key = Objects.toString(json.get("Key"), null);
        final Map newKey = (Map) json.getOrDefault("NewKey", Collections.emptyMap());
        this.key = Objects.toString(newKey.get("value"), key);
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return key;
    }
}

以上代码打印:

null
key
newkey
newkey
newkey
© www.soinside.com 2019 - 2024. All rights reserved.