首页 > 解决方案 > 如何将 Json 中的顶级元素映射到 Java 类

问题描述

我需要将输入的 json 字符串解析为 Java 对象。我为此使用杰克逊注释。

输入Json:-

{
"employee":{
  "id":123,
  "name":abc,
    department:{
      "id":123,
      "name":"xyz"
    }
  }
}

Pojo 文件:-

public class Employee {

@JsonProperty("name")
protected String name;
@JsonProperty("department")
protected List<Department> departments;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public List<Department> getDepartment() {
    return departments;
}
public void setDepartment(List<Department> departments) {
    this.departments = departments;
}
}

mapper.readValue(jsonString, Employee.class)使用语句时出现以下异常:

线程“main”com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException 中的异常:无法识别的字段“employee”

如果我@JsonIgnoreProperties(ignoreUnknown=true)什么都不使用,则映射到我的 Employee 对象。有人可以建议我缺少什么吗?

谢谢,

标签: javajsonparsingjacksonpojo

解决方案


推荐阅读