com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "FileSize"
请求阿里云的OSS接口图片信息,返回json格式的数据,通过ObjectMapper将json转为Image对象时候报错转换失败
将json转对象的代码:
String jsonStr = "{\n" +
" \"FileSize\": {\"value\": \"25929\"},\n" +
" \"Format\": {\"value\": \"jpg\"},\n" +
" \"ImageHeight\": {\"value\": \"200\"},\n" +
" \"ImageWidth\": {\"value\": \"300\"},\n" +
" \"ResolutionUnit\": {\"value\": \"1\"},\n" +
" \"XResolution\": {\"value\": \"100/1\"},\n" +
" \"YResolution\": {\"value\": \"100/1\"}}";
ObjectMapper objectMapper = new ObjectMapper();
Image image = objectMapper.readValue(jsonStr, Image.class);
报错信息:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "FileSize" (class com.xxx.xxx.bean.Image), not marked as ignorable (7 known properties: "resolutionUnit", "imageHeight", "xresolution", "yresolution", "format", "imageWidth", "fileSize"])
at [Source: {
"FileSize": {"value": "25929"},
"Format": {"value": "jpg"},
"ImageHeight": {"value": "200"},
"ImageWidth": {"value": "300"},
"ResolutionUnit": {"value": "1"},
"XResolution": {"value": "100/1"},
"YResolution": {"value": "100/1"}}; line: 2, column: 18] (through reference chain: com.xxx.xxx.bean.Image["FileSize"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:834)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1093)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1489)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1467)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:282)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
at com.xxx.xxx.service.PostOssService.main(OssService.java:103)
原因:
Image对象中缺少json的某个字段属性引起
解决:
1、加上如下两行代码:
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
2、在需要转化的对象的类中添加注解,注解信息如下:
@JsonIgnoreProperties(ignoreUnknown = true)
参考:
https://stackoverflow.com/questions/51034173/backblazetokenresponse-com-fasterxml-jackson-databind-exc-unrecognizedproperty
https://blog.csdn.net/qq_30739519/article/details/51273544