gpt4 book ai didi

java - Jackson默认将列表反序列化为ArrayList吗?

转载 作者:行者123 更新时间:2023-12-01 09:14:50 28 4
gpt4 key购买 nike

我运行以下代码片段:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class JsonMapper {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

public static <T> String toJson(final T object) throws JsonProcessingException {
return OBJECT_MAPPER.writeValueAsString(object);
}

public static <T> T fromJson(final String json, final Class<T> clazz) throws IOException {
return OBJECT_MAPPER.readValue(json, clazz);
}

public static <T> T fromJson(final String json, final TypeReference<T> type) throws IOException {
return OBJECT_MAPPER.readValue(json, type);
}
public static void main(String args[]) throws IOException {
String json = "[1,2,3]";
// TEST1: initialize TypeReference with type ArrayList
List<Integer> expected = JsonMapper.fromJson(json, new TypeReference<ArrayList<Integer>>(){});
System.out.println(expected.getClass().getName());
// TEST2: initialize TypeReference with type List
expected = JsonMapper.fromJson(json, new TypeReference<List<Integer>>(){});
System.out.println(expected.getClass().getName());
// TEST3: initialize TypeReference with type LinkedList
expected = JsonMapper.fromJson(json, new TypeReference<LinkedList<Integer>>(){});
System.out.println(expected.getClass().getName());

}
}

输出是:

java.util.ArrayList
java.util.ArrayList
java.util.LinkedList

当我用 ArrayListList 类型初始化 TypeReference 时,变量预期的类型是 ArrayList ,但如果我用 LinkedList 类型初始化 TypeReference,它就会变成 LinkedList。那么,jackson 默认情况下会将字符串列表反序列化为 ArrayList 吗?

最佳答案

是的,jackson 默认将字符串列表反序列化为 ArrayList。代码位于 com.fasterxml.jackson.databind.deser.impl.CreatorCollector 类中:

    @Override
public Object createUsingDefault(DeserializationContext ctxt) throws IOException {
switch (_type) {
case TYPE_COLLECTION: return new ArrayList<Object>();
case TYPE_MAP: return new LinkedHashMap<String,Object>();
case TYPE_HASH_MAP: return new HashMap<String,Object>();
}
throw new IllegalStateException("Unknown type "+_type);
}

关于java - Jackson默认将列表反序列化为ArrayList吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40634953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com