您的位置:首页 >Jackson 解析嵌套 JSON 到 Map 方法
发布于2026-01-30 阅读(0)
扫一扫,手机访问

本文详解 Jackson 库中处理多层嵌套 JSON(如 `"resources": {"key": {"value": "test"}}`)时的 Java 类型映射技巧,重点解决因泛型擦除和类型不匹配导致的 `MismatchedInputException` 异常,并提供可直接运行的类型安全方案。
你的 JSON 结构本质上是一个三层嵌套的键值映射:
{
"resources": {
"foo": { "value": "test" },
"bar": { "value": "test" }
}
}对应逻辑为:
"resources" → Map<String, ?>,其中每个 value 是一个 Map<String, String>(例如 "foo" → {"value": "test"})。
因此,理想的目标类型应为:
Map<String, Map<String, String>>
而你原始类中使用的:
private HashMap<String, HashMap<String, List<String>>> stringListHashMap;
存在两个关键错误:
✅ 正确做法是精确匹配 JSON 层级与 Java 类型,并借助 TypeReference 避免泛型擦除问题。
直接使用 ObjectMapper.readValue() 配合 TypeReference,声明目标类型为 Map<String, Map<String, String>>:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.HashMap;
import java.util.Map;
public class JacksonNestedJsonExample {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = """
{
"resources": {
"foo": { "value": "test" },
"bar": { "value": "demo" }
}
}
""";
// 使用 TypeReference 显式指定完整泛型类型
Map<String, Map<String, String>> result = mapper.readValue(json,
new TypeReference<Map<String, Map<String, String>>>() {});
// 提取 resources 内容
Map<String, String> resources = result.get("resources");
System.out.println(resources.get("foo")); // {value=test}
System.out.println(resources.get("foo").get("value")); // test
}
}定义清晰、语义化的 POJO 类,提升可读性与可维护性:
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
public class JsonTwoJavaFileModel {
@JsonProperty("resources")
private Map<String, ResourceEntry> resources;
// 内部类:代表每个资源项(如 "foo")
public static class ResourceEntry {
private String value;
// getter/setter(Jackson 默认需要)
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
// getter for resources
public Map<String, ResourceEntry> getResources() {
return resources;
}
}使用方式:
JsonTwoJavaFileModel model = mapper.readValue(json, JsonTwoJavaFileModel.class);
String fooValue = model.getResources().get("foo").getValue(); // "test"通过精准建模与 TypeReference 的配合,即可优雅、健壮地解析任意深度的嵌套 JSON,彻底规避 MismatchedInputException。
上一篇:微信拉黑和删除的区别详解
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9