You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jackson读取以方括号开头的JSON数组?

用Jackson读取JSON数组(方括号开头的JSON)

当JSON以方括号开头时,它表示一个数组/列表,而非单个对象,因此不能直接映射到单个Person类,需要对应到集合类型或数组类型,以下是几种常用实现方式:

方法1:使用TypeReference读取为List<Person>

通过TypeReference明确泛型类型,让Jackson正确解析集合:

ObjectMapper mapper = new ObjectMapper();
List<Person> personList = mapper.readValue(fileReader, new TypeReference<List<Person>>() {});

方法2:直接读取为Person数组

这种方式更简洁,适合不需要直接使用List的场景:

ObjectMapper mapper = new ObjectMapper();
Person[] personArray = mapper.readValue(fileReader, Person[].class);

// 若需要转换为List,可使用Arrays.asList()
List<Person> personList = Arrays.asList(personArray);
// 注意:Arrays.asList返回固定大小的列表,若需要可修改的List,转成ArrayList:
List<Person> mutableList = new ArrayList<>(Arrays.asList(personArray));

方法3:使用CollectionType构建自定义集合类型

如果需要指定具体的List实现(比如ArrayList),可以用TypeFactory构建类型:

ObjectMapper mapper = new ObjectMapper();
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Person.class);
List<Person> personList = mapper.readValue(fileReader, listType);

注意事项

  • Person类必须包含无参构造器,Jackson默认依赖它实例化对象;
  • 类的字段名需与JSON中的键名一致,若不一致可使用@JsonProperty注解映射,比如:
    @JsonProperty("firstName")
    private String firstName;
    
  • 确保字段有对应的getter/setter方法,或者使用Lombok的@Data注解自动生成。

内容的提问来源于stack exchange,提问作者Paul Marcelin Bejan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:22:15