一、用法
加在实体类上
@JsonIgnoreProperties(ignoreUnknown = true)
二、目的
防止Json转成实体类时因为字段的缺少或过多而报错
三、经验
在微服务架构中,我们一般在OpenFeign在DTO对象上加@JsonIgnoreProperties
注解,防止OpenFegin接口提供方在DTO对象上加了新字段,调用OpenFeign的客户端DTO没有及时加上新字段,导致系统报错。
四、用法举例说明
1、Java实体类
public class Book {
private String name;
private String price;
}
2、如果json 字符串中的字段数量多于类的字段,如:
String bookJson3 = "{\"name\":\"d2\", \"price\":\"1\", \"sn\":\"222\"}";
Book b3 = mapper.readValue(bookJson3, Book.class);
那么报错如下
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field
"sn" (class com.example.demo.DemoApplicationTests2$Book),
not marked as ignorable (2 known properties: "price", "name"])
at [Source: (String)"{"name":"d2", "price":"1", "sn":"222"}"; line: 1, column: 34]
(through reference chain: com.example.demo.DemoApplicationTests2$Book["sn"])
3、给Book 类增加注解:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Book {
private String name;
private String price;
}
可以解决这个问题。
4、如果 json 字符串中的字段少了是可以正常工作的,如
String bookJson = "{\"name\":\"dd\"}";
Book b = mapper.readValue(bookJson, Book.class);
System.out.println(b.name);
System.out.println(b.price);
打印
dd
null
网友评论