Jackson Deserializer列出具有ContextualDeserializer的通用类型

时间:2018-04-22 09:26:38

标签: java json generics jackson

我有这个json对象

[
  {"name": "Alice","age": 37},
  {"name": "Bob","age": 37}
]

我看到了这个例子并且它有效,我怎样才能将它改编为人员列表

How to create a custom deserializer in Jackson for a generic type?

    public static class Wrapper<T> {
       public T value;
    }

    public class People {
        public List<Person> people;
    }

    public class Person {
        public Wrapper<String> name;
        public Wrapper<Integer> age;
    }

我想使用JsonDeserializeContextualDeserializer使用java泛型类型的人员列表反序列化Json对象,以便您可以将该类用于其他对象

public static class WrapperDeserializer extends JsonDeserializer<Wrapper<?>> 
       implements ContextualDeserializer {
    ...........

        }

并获取人员列表

SimpleModule module = new SimpleModule()
        .addDeserializer(Wrapper.class, new WrapperDeserializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);

String json = "[{ \"name\": \"Alice\",\"age\": 37},{ \"name\": \"Bob\",\"age\": 37}]";

People people = objectMapper.readValue(json, People.class);

0 个答案:

没有答案