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

如何用Jackson ObjectMapper获取JSON对象数组大小(不使用Jackson Tree)

解决方法:用Jackson ObjectMapper获取JSON数组大小(不使用Tree模型)

嘿,我明白你的问题啦!你的JSON是数组格式的内容,但你当前的代码是把它当成单个IndexPortion对象来解析,这就是问题所在——直接解析会报错,更别说获取数组大小了。不用Tree模型的话,我们可以直接把JSON数组解析成List<IndexPortion>,然后就能轻松拿到大小了。

具体步骤和代码示例:

首先,修改你的解析代码,把目标类型改成List<IndexPortion>。这里推荐用TypeReference来避免泛型类型擦除的问题:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;

// 初始化ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();

// 将JSON数组解析为List<IndexPortion>
List<IndexPortion> indexPortionList = objectMapper.readValue(
    new File(path),
    new TypeReference<List<IndexPortion>>() {}
);

// 获取数组的大小
int arraySize = indexPortionList.size();
// 这里会输出2,对应你示例里的两个对象
System.out.println("JSON数组中对象的数量:" + arraySize);

另一种方式(用CollectionType):

如果你不想用TypeReference,也可以通过ObjectMapper的TypeFactory来构建集合类型:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.File;
import java.util.List;

ObjectMapper objectMapper = new ObjectMapper();
// 构建List<IndexPortion>的类型
CollectionType listType = objectMapper.getTypeFactory()
    .constructCollectionType(List.class, IndexPortion.class);

List<IndexPortion> indexPortionList = objectMapper.readValue(new File(path), listType);
int arraySize = indexPortionList.size();

为什么原来的代码不行?

你提供的JSON示例是:

[{"index":"incident","type":"SmbIncident"}, {"index":"incident","type":"SmbIncident"} ]

它的根节点是数组(用[]包裹),而你原来的代码new ObjectMapper().readValue(new File(path), IndexPortion.class)是在尝试解析单个对象(用{}包裹),所以Jackson会抛出JsonMappingException,提示无法将数组映射到单个对象。

通过解析成List<IndexPortion>,Jackson会自动把数组里的每个元素转换成IndexPortion对象,存入List中,之后调用size()就能直接得到数组里的对象数量啦。

内容的提问来源于stack exchange,提问作者Kamran Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:30:38