且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何反序列化泛型 List<T>与杰克逊?

更新时间:2023-01-17 08:26:40

之所以这样工作,是因为Java 中的类型擦除.在开始阅读本答案的下一部分之前,请先阅读一下:

您现在可能知道,在阅读以上文章后,您编译后的方法如下所示:

static 类型引用listOf(Class 忽略){return new TypeReference(){};}

Jackson 将尝试为它找出最合适的类型,即 java.util.LinkedHashMap 用于 JSON 对象.要创建 irrefutable type 你需要使用 com.fasterxml.jackson.databind.type.TypeFactory 类.见下例:

import com.fasterxml.jackson.core.type.TypeReference;导入 com.fasterxml.jackson.databind.JavaType;导入 com.fasterxml.jackson.databind.ObjectMapper;导入 com.fasterxml.jackson.databind.type.TypeFactory;导入 java.io.File;导入 java.util.List;公共类 JsonTypeApp {public static void main(String[] args) 抛出异常 {File jsonFile = new File("./resource/test.json").getAbsoluteFile();ObjectMapper mapper = new ObjectMapper();System.out.println("尝试使用'TypeFactory'");列表ids = mapper.readValue(jsonFile, CollectionsTypeFactory.listOf(Id.class));System.out.println(ids);id id1 = ids.get(0);System.out.println(id1);System.out.println("尝试使用'TypeReference>'");列表地图 = mapper.readValue(jsonFile, CollectionsTypeFactory.erasedListOf(Id.class));System.out.println(地图);id maps1 = maps.get(0);System.out.println(maps1);}}类集合类型工厂{静态 JavaType listOf(Class clazz) {返回 TypeFactory.defaultInstance().constructCollectionType(List.class, clazz);}静态 <T>类型引用erasedListOf(Class 被忽略) {return new TypeReference(){};}}班级号 {私有整数 ID;//getter、setter、toString}

以上示例,对于以下 JSON 负载:

[{身份证":1},{身份证":22},{身份证":333}]

印刷品:

尝试使用TypeFactory"[{1}、{22}、{333}]{1}尝试使用 'TypeReference>'[{id=1}, {id=22}, {id=333}]线程main"中的异常 java.lang.ClassCastException:java.util.LinkedHashMap 无法转换为 com.example.Id在 com.example.JsonTypeApp.main(JsonTypeApp.java:27)

另见:

I've been using Jackson to serialize/deserialize objects for years and have always found it needlessly complicated to use TypeReference<T> to deserialize List etc. I created a simple helper function:

public static <T> TypeReference<List<T>> list() {
    return new TypeReference<List<T>>(){}
}

With intended use:

List<Foo> foos = objectMapper.readValue(json, list());

And it works! Kind of. When inspecting through the debugger, rather than a list of Foo, it is rather a list of LinkedHashMap. I understand that ObjectMapper deserializes into LinkedHashMap for type Object and I read the explanation for that here:

Jackson and generic type reference

However, why is it able to assign List<LinkedHasMap> to a List<Foo>? At the very least shouldn't that be some sort of ClassCastException?

Also, is there anyway to do this with Java's type system?

NOTE: the following method declaration has the same issue, which makes sense because the additional argument is not needed for T to be determined:

public static <T> TypeReference<List<T>> listOf(Class<T> ignored) {
    return new TypeReference<List<T>>(){}
}

It works like this because of type erasure in Java. Please, read about it before you start reading next part of this answer:

As you probably know right now, after reading above articles, your method after compilation looks like this:

static <T> TypeReference<List> listOf(Class<T> ignored) {
    return new TypeReference<List>(){};
}

Jackson will try to find out the most appropriate type for it which will be java.util.LinkedHashMap for a JSON Object. To create irrefutable type you need to use com.fasterxml.jackson.databind.type.TypeFactory class. See below example:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.File;
import java.util.List;

public class JsonTypeApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        System.out.println("Try with 'TypeFactory'");
        List<Id> ids = mapper.readValue(jsonFile, CollectionsTypeFactory.listOf(Id.class));
        System.out.println(ids);
        Id id1 = ids.get(0);
        System.out.println(id1);

        System.out.println("Try with 'TypeReference<List<T>>'");
        List<Id> maps = mapper.readValue(jsonFile, CollectionsTypeFactory.erasedListOf(Id.class));
        System.out.println(maps);
        Id maps1 = maps.get(0);
        System.out.println(maps1);
    }
}

class CollectionsTypeFactory {
    static JavaType listOf(Class clazz) {
        return TypeFactory.defaultInstance().constructCollectionType(List.class, clazz);
    }

    static <T> TypeReference<List> erasedListOf(Class<T> ignored) {
        return new TypeReference<List>(){};
    }
}

class Id {
    private int id;

    // getters, setters, toString
}

Above example, for below JSON payload:

[
  {
    "id": 1
  },
  {
    "id": 22
  },
  {
    "id": 333
  }
]

prints:

Try with 'TypeFactory'
[{1}, {22}, {333}]
{1}
Try with 'TypeReference<List<T>>'
[{id=1}, {id=22}, {id=333}]
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.Id
    at com.example.JsonTypeApp.main(JsonTypeApp.java:27)

See also: