Jackson with JSON: Unrecognized field, not marked as ignorable(杰克逊与 JSON:无法识别的字段,未标记为可忽略)
问题描述
我需要将某个 JSON 字符串转换为 Java 对象.我正在使用杰克逊进行 JSON 处理.我无法控制输入 JSON(我从 Web 服务中读取).这是我的输入 JSON:
I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:
{"wrapper":[{"id":"13","name":"Fred"}]}
这是一个简化的用例:
private void tryReading() {
String jsonStr = "{"wrapper":[{"id":"13","name":"Fred"}]}";
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = null;
try {
wrapper = mapper.readValue(jsonStr , Wrapper.class);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("wrapper = " + wrapper);
}
我的实体类是:
public Class Student {
private String name;
private String id;
//getters & setters for name & id here
}
我的 Wrapper 类基本上是一个容器对象,用于获取我的学生列表:
My Wrapper class is basically a container object to get my list of students:
public Class Wrapper {
private List<Student> students;
//getters & setters here
}
我不断收到此错误,并且包装器"返回 null
.我不确定缺少什么.有人可以帮忙吗?
I keep getting this error and "wrapper" returns null
. I am not sure what's missing. Can someone help please?
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
at [Source: java.io.StringReader@1198891; line: 1, column: 13]
(through reference chain: Wrapper["wrapper"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
.from(UnrecognizedPropertyException.java:53)
推荐答案
可以使用Jackson的类级注解:
You can use Jackson's class-level annotation:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties
class { ... }
它将忽略您在 POJO 中未定义的所有属性.当您只是在 JSON 中寻找几个属性并且不想编写整个映射时非常有用.更多信息请访问 Jackson 网站.如果你想忽略任何未声明的属性,你应该写:
It will ignore every property you haven't defined in your POJO. Very useful when you are just looking for a couple of properties in the JSON and don't want to write the whole mapping. More info at Jackson's website. If you want to ignore any non declared property, you should write:
@JsonIgnoreProperties(ignoreUnknown = true)
这篇关于杰克逊与 JSON:无法识别的字段,未标记为可忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:杰克逊与 JSON:无法识别的字段,未标记为可忽略


基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01