杰克逊嵌套对象图实现

时间:2018-11-23 07:08:53

标签: java jackson

有什么办法告诉杰克逊图书馆想在嵌套对象中使用Map实现吗? 我从HashMap扩展了一些Map,我不在乎字段顺序

public class FieldsMap<K, V> extends HashMap<K, V> {
  @Override
  public V get(Object field) {
    V value = super.get(field);
    if (value == null && !containsKey(field)) {
      log.warn("Query unknown field " + field);
    }
    return value;
  }
}

然后ObjectMapper.readValue返回此类

final TypeReference<FieldsMap<String, Object>> mapType =
    new TypeReference<FieldsMap<String, Object>>() {};

Map<String, Object> res = new ObjectMapper().readValue("{\"a\": {\"b\": 0}}", mapType);
res.get("c"); // warning

但是嵌套对象始终是LinkedHashMap

System.out.println(res.get("a").getClass().getName()); // java.util.LinkedHashMap
((Map)res.get("a")).get("c"); // no warning

在测试环境中将很有帮助。

1 个答案:

答案 0 :(得分:1)

必须将抽象类型映射添加到ObjectMapper。这是通过模块完成的:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FieldsMap<K, V> extends HashMap<K, V> {

    @Override
    public V get(Object field) {
        V value = super.get(field);
        if (value == null && !containsKey(field)) {
            System.out.println("Query unknown field " + field);
        }
        return value;
    }

    public static void main(String [] args) throws IOException {
        final TypeReference<FieldsMap<String, Object>> mapType = new TypeReference<FieldsMap<String, Object>>() {};
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule().addAbstractTypeMapping(Map.class, FieldsMap.class);
        objectMapper.registerModule(module);
        Map<String, Object> res = objectMapper.readValue("{\"a\": {\"b\": 0}}", mapType);
        res.get("c");
        System.out.println(res.get("a").getClass().getName());
        ((Map)res.get("a")).get("c");
    }
}

这将指示Jackson在每次需要FieldsMap时使用您的自定义类型Map

输出为:

Query unknown field c
FieldsMap
Query unknown field c