【问题标题】:How Jackson handles mapping conflict?Jackson 如何处理映射冲突?
【发布时间】:2020-04-16 13:43:33
【问题描述】:

我有以下类,其属性“键”映射到 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?试图了解杰克逊如何处理冲突。我可以指定订单吗?例如,如果我希望 key 始终映射到 NewKey,如果 KeyNewKey 都存在于 json 中,我该怎么办?

【问题讨论】:

  • 你试过了吗?你有什么错误吗?

标签: java json jackson json-deserialization jackson2


【解决方案1】:

在您的示例中,您使用@JsonAlias("Key")@JsonProperty("NewKey") 的顺序取决于JSON 有效负载中key-value 对的顺序。如果您想始终以 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

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 2012-10-15
    • 2012-04-30
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2013-09-01
    • 2015-04-07
    相关资源
    最近更新 更多