jackson 的UnrecognizedPropertyException错误
前段时间,使用jackson封装了json字符串转换为javabean的方法,代码如下:
- public static <T> T renderJson2Object(String json, Class clazz){
- if(!StringUtil.checkObj(json)){
- return null;
- }
- try {
- mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
- DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- mapper.getSerializationConfig().setDateFormat(myDateFormat);
- return (T)mapper.readValue(json, clazz);
- } catch (IOException e) {
- log.error(e);
- throw new IllegalArgumentException(e);
- }
- }
public static <T> T renderJson2Object(String json, Class clazz){
if(!StringUtil.checkObj(json)){
return null;
}
try {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.getSerializationConfig().setDateFormat(myDateFormat);
return (T)mapper.readValue(json, clazz);
} catch (IOException e) {
log.error(e);
throw new IllegalArgumentException(e);
}
}
,这个方法可以根据json字符串,转换为clazz指定的类型的对象,如:
- renderJson2Object("{\"name\":\"china\",\"age\":\"<span style="white-space: normal;">5000</span>\"}",Student.class);
renderJson2Object("{\"name\":\"china\",\"age\":\"5000\"}",Student.class);
Student类里有name,age的get,set方法,代码如下:
- public class Student implements Serializable{
- private static final long serialVersionUID = 685922460589405829L;
- private String name;
- private String age;
- /*get set略*/
- }
public class Student implements Serializable{
private static final long serialVersionUID = 685922460589405829L;
private String name;
private String age;
/get set略/
}
根据上面的json字符串可以正常转换为Student对象,
但是通常情况下,从前端传json字符串到后端,json字符串的值是不可控的或者被框架修改了json字符串,如在里面添加了其他的键值对,
如现在的json字符串为:"{\"address\":\"hunan\",\"name\":\"china\",\"age\":\"5000\"}",
Student类里根本没有address属性,这样的情况下使用renderJson2Object方法时,会抛
- java.lang.IllegalArgumentException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "address" (Class util.Student), not marked as ignorable
java.lang.IllegalArgumentException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "address" (Class util.Student), not marked as ignorable
意思是说Student类里没有address这个属性,所以无法正常转化,同时还指明了not marked as ignorable,即没有标明可忽略的特性,先看源码这句话的理解这句话的意思
类:org.codehaus.jackson.map.deser.BeanDeserializer中的
- @Override
- protected void handleUnknownProperty(JsonParser jp, DeserializationContext ctxt, Object beanOrClass, String propName)
- throws IOException, JsonProcessingException
- {
- ... ... ...
- <span style="color: #ff0000;">// If registered as ignorable, skip</span>
- <span style="color: #ff0000;">if (_ignoreAllUnknown ||
- (_ignorableProps != null && _ignorableProps.contains(propName))) {
- jp.skipChildren();
- return;
- }</span>
- ... ... ...
- }
@Override
protected void handleUnknownProperty(JsonParser jp, DeserializationContext ctxt, Object beanOrClass, String propName)
throws IOException, JsonProcessingException
{
... ... ...
// If registered as ignorable, skip
if (_ignoreAllUnknown ||
(_ignorableProps != null && _ignorableProps.contains(propName))) {
jp.skipChildren();
return;
}
... ... ...
}
源码注释说,如果注册了忽略特性,则会跳过此步骤,那到底需要怎么忽略呢?
请再看类:org.codehaus.jackson.map.deser.BeanDeserializerFactory中的
- protected void addBeanProps(DeserializationConfig config,
- BasicBeanDescription beanDesc, BeanDeserializerBuilder builder)
- throws JsonMappingException
- {
- ... .... ...
- // Things specified as "ok to ignore"? [JACKSON-77]
- AnnotationIntrospector intr = config.getAnnotationIntrospector();
- boolean ignoreAny = false;
- {
- Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());
- if (B != null) {
- ignoreAny = B.booleanValue();
- builder.setIgnoreUnknownProperties(ignoreAny);
- }
- }
- ... ... ...
- }
protected void addBeanProps(DeserializationConfig config,
BasicBeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
... .... ...
// Things specified as "ok to ignore"? [JACKSON-77]
AnnotationIntrospector intr = config.getAnnotationIntrospector();
boolean ignoreAny = false;
{
Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());
if (B != null) {
ignoreAny = B.booleanValue();
builder.setIgnoreUnknownProperties(ignoreAny);
}
}
... ... ...
}
intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());
会查找目标对象中,是否使用了JsonIgnoreProperties 注解,其中把注解的value值赋给了builder.setIgnoreUnknownProperties(ignoreAny);
到此Student类的正确做法为:
- <span style="color: #ff0000;">@JsonIgnoreProperties(ignoreUnknown = true) </span>
- public class Student implements Serializable{
- private static final long serialVersionUID = 685922460589405829L;
- private String name;
- private String age;
- /*get set.....*/
- }
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student implements Serializable{
private static final long serialVersionUID = 685922460589405829L;private String name;
private String age;
/get set...../
}
看红色注解,现在暂时找到在类中添加注解(感觉具体的pojo对象和jackson耦合),不知道有没有其他方法,设全局变量来控制,如果有朋友知道,请告诉我谢谢。。。
谢谢 up2pu 兄弟的帮助,使用mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false),
则无需在目标类中添加JsonIgnoreProperties注解
发表评论
<p style="text-align:right;margin-right:30px;">(快捷键 Alt+S / Ctrl+Enter) <input class="submit" id="quick_reply_button" name="commit" type="submit" value="提交"></p>
</form>
<script type="text/javascript">
new HotKey("s",function() {$('quick_reply_button').click();},{altKey: true, ctrlKey: false});
new HotKey(new Number(13),function() {$('quick_reply_button').click();},{altKey: false, ctrlKey: true});
new Validation("comment_form", {immediate: false, onFormValidate: function(result, form){
if(result) {
new Ajax.Request('/blog/create_comment/1131059', {
onFailure:function(response){
$('comments').insert({after:response.responseText})
form.spinner.hide();
Element.scrollTo($('comments'));
},
onSuccess:function(response){
Element.scrollTo($('comments'));
var new_comment = new Element('div', {}).update(response.responseText).firstChild;
var comment_id = new_comment.readAttribute('id');
$('comments').insert({after:response.responseText});
$('editor_body').value = "";
var css_rules = '#' + comment_id + ' pre';
highlightNewAddContent(css_rules);
processComment();
code_favorites_init(css_rules);
form.spinner.hide();
}, parameters:Form.serialize(form)
});
}
}});
</script>
</div>
jackson 的UnrecognizedPropertyException错误的更多相关文章
- jackson 常见问题
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type org.codehaus ...
- springMvc 4.0 jackson包改变
使用之前的json包出包java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException错误. sp ...
- 【maven 报错】maven项目执行maven install时报错Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
在使用maven新建的web项目中,执行 执行如上的这两个操作,报错: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-co ...
- SpringMVC+Spring+mybatis项目从零开始--Spring mybatis mysql配置实现
上一章我们把SSM项目结构已搭建(SSM框架web项目从零开始--分布式项目结构搭建)完毕,本章将实现Spring,mybatis,mysql等相关配置. 1. 外部架包依赖引入 外部依赖包引入 ...
- maven搭建ssm框架问题总结
1. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.0:compile (default-comp ...
- 航空概论(历年资料,引之百度文库,PS:未调格式,有点乱)
航空航天尔雅 选择题1. 已经实现了<天方夜谭>中的飞毯设想.—— A——美国2. 地球到月球大约—— C 38 万公里3. 建立了航空史上第一条定期空中路线—— B——德国4. 对于孔明 ...
- Jackson反序列化错误:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field的解决方法
说明:出现这种问题的情况是由于JSON里面包含了实体没有的字段导致反序列化失败. 解决方法: // 第一种解决方案 // ObjectMapper对象添加 mapper.configure(Deser ...
- jackson json转实体对象 com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
Jackson反序列化错误:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field的解 ...
- spring-data-jpa 中,如果使用了one-to-many , many-to-one的注释,会在Jackson进行json字符串化的时候出现错误
问题: spring-data-jpa 中,如果使用了one-to-many , many-to-one的注释,会在Jackson 2.7.0 进行json字符串化的时候出现错误. 解决办法: 通过在 ...
随机推荐
- P4744 A’s problem(a)
时间: 1000ms / 空间: 655360KiB / Java类名: Main 背景 冬令营入学测试题,每三天结算一次成绩.参与享优惠 描述 这是一道有背景的题目,小A也是一个有故事的人.但可惜的 ...
- mysql 删除 一天前 创建 的数据,计算时间差
DELETE from table_name WHERE TIMESTAMPDIFF(SECOND ,CREATE_TIME,now() ) > 24*60*60 https://www.cnb ...
- mysql零散操作
添加对外用户 CREATE USER 'admin'@'%' IDENTIFIED BY '!QAZ2wsx'; GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%'; ...
- linux磁盘满了怎么办??删掉无用的大文件
今天公司网站突然无法访问,因为之前遇到过是因为磁盘问题,所以使用 df 命令查看结果,结果果然是有100%的东西,那么怎么解决呢,我们想到得查找大文件,并删掉无用的大文件比如log 那么linux如何 ...
- stark组件(2):提取公共视图函数、URL分发和设置别名
效果图: Handler类里处理的增删改查.路由分发.给URL设置别名等包括以后还要添加的很多功能,每一个数据库的类都需要,所以我们要把Handler提取成一个基类.提取成基类后,每一个数据表都可以继 ...
- 笔记-python-standard library-8.5.heapq
笔记-python-standard library-8.5.heapq 1. heapq-heap queue algorithm源码:Lib/heapq.pythis module provide ...
- android静默安装和智能安装(转)
Android 静默安装和智能安装的实现方法 http://blog.csdn.net/fuchaosz/article/details/51852442 Android静默安装实现方案,仿360手机 ...
- DiyCode开源项目 TopicActivity 分析
1.首先看看TopActivity效果. 2.TopicActivity是一个继承BaseActivity的.前面分析过BaseActivity了.主要有一个标题栏,有返回的图标. 3.贴一下T ...
- android json 解析 kotlin
前面 写了一次 kotlin解析json 但是,真的写得太烂,直接删掉了,现在重新整理一下.顺便记录一下今天坑了我很久的小问题. 1.首先从最简单的入手吧 一个json的字符串:=====就叫做jso ...
- 微信SSL证书更换的检查与安装方法
Ubuntu, Debian 查看根证书 确认操作系统上,是否存在以下文件: /etc/ssl/certs/DigiCert_Global_Root_CA.pem /etc/ssl/certs/Bal ...