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:无法识别的字段,未标记为可忽略
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01