static class Book {
String name;
String price;
}
例一
这样一个类,如果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"])
给Book 类增加注解:
@JsonIgnoreProperties(ignoreUnknown = true)
可以解决这个问题。
例二
如果 json 字符串中的字段少了是可以正常工作的,如
String bookJson = "{\"name\":\"dd\"}";
Book b = mapper.readValue(bookJson, Book.class);
System.out.println(b.name);
System.out.println(b.price);
输出为:
dd
null
例三
b = new Book();
b.name = "hhg";
System.out.println(mapper.writeValueAsString(b));
以上代码可以正常工作,输出为:
{"name":"hhg","price":null}