前段时间,使用jackson封装了json字符串转换为javabean的方法,代码如下:

  1. public static <T> T renderJson2Object(String json, Class clazz){
  2. if(!StringUtil.checkObj(json)){
  3. return null;
  4. }
  5. try {
  6. mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
  7. DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  8. mapper.getSerializationConfig().setDateFormat(myDateFormat);
  9. return (T)mapper.readValue(json, clazz);
  10. } catch (IOException e) {
  11. log.error(e);
  12. throw new IllegalArgumentException(e);
  13. }
  14. }
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指定的类型的对象,如:

  1. 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方法,代码如下:

  1. public class Student implements Serializable{
  2. private static final long serialVersionUID = 685922460589405829L;
  3. private String name;
  4. private String age;
  5. /*get set略*/
  6. }
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方法时,会抛

  1. 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中的

  1. @Override
  2. protected void handleUnknownProperty(JsonParser jp, DeserializationContext ctxt, Object beanOrClass, String propName)
  3. throws IOException, JsonProcessingException
  4. {
  5. ... ... ...
  6. <span style="color: #ff0000;">// If registered as ignorable, skip</span>
  7. <span style="color: #ff0000;">if (_ignoreAllUnknown ||
  8. (_ignorableProps != null && _ignorableProps.contains(propName))) {
  9. jp.skipChildren();
  10. return;
  11. }</span>
  12. ... ... ...
  13. }
@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中的

  1. protected void addBeanProps(DeserializationConfig config,
  2. BasicBeanDescription beanDesc, BeanDeserializerBuilder builder)
  3. throws JsonMappingException
  4. {
  5. ... .... ...
  6. // Things specified as "ok to ignore"? [JACKSON-77]
  7. AnnotationIntrospector intr = config.getAnnotationIntrospector();
  8. boolean ignoreAny = false;
  9. {
  10. Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo());
  11. if (B != null) {
  12. ignoreAny = B.booleanValue();
  13. builder.setIgnoreUnknownProperties(ignoreAny);
  14. }
  15. }
  16. ... ... ...
  17. }
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类的正确做法为:

  1. <span style="color: #ff0000;">@JsonIgnoreProperties(ignoreUnknown = true) </span>
  2. public class Student implements Serializable{
  3. private static final long serialVersionUID = 685922460589405829L;
  4. private String name;
  5. private String age;
  6. /*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错误的更多相关文章

  1. jackson 常见问题

    org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type   org.codehaus ...

  2. springMvc 4.0 jackson包改变

    使用之前的json包出包java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException错误. sp ...

  3. 【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 ...

  4. SpringMVC+Spring+mybatis项目从零开始--Spring mybatis mysql配置实现

    上一章我们把SSM项目结构已搭建(SSM框架web项目从零开始--分布式项目结构搭建)完毕,本章将实现Spring,mybatis,mysql等相关配置. 1.    外部架包依赖引入 外部依赖包引入 ...

  5. maven搭建ssm框架问题总结

    1. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.0:compile (default-comp ...

  6. 航空概论(历年资料,引之百度文库,PS:未调格式,有点乱)

    航空航天尔雅 选择题1. 已经实现了<天方夜谭>中的飞毯设想.—— A——美国2. 地球到月球大约—— C 38 万公里3. 建立了航空史上第一条定期空中路线—— B——德国4. 对于孔明 ...

  7. Jackson反序列化错误:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field的解决方法

    说明:出现这种问题的情况是由于JSON里面包含了实体没有的字段导致反序列化失败. 解决方法: // 第一种解决方案 // ObjectMapper对象添加 mapper.configure(Deser ...

  8. jackson json转实体对象 com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

    Jackson反序列化错误:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field的解 ...

  9. 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字符串化的时候出现错误. 解决办法: 通过在 ...

随机推荐

  1. Beyond Compare在Mac下永久试用

    转自 作者:忆如初 链接:https://www.jianshu.com/p/596b4463eacd 来源:简书 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处. 亲测可用 一. ...

  2. git出现误修改如何撤销

    场景1:当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令git checkout -- file. 场景2:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步, ...

  3. django 图片上传与显示

    由于图片上传的需要,学习了一波上传 1. 上传 前端代码 <form action="写上相应的定向位置" method="post" enctype=& ...

  4. ZendFramework-2.4 源代码 - 关于MVC - Model层

    所谓的谓词Predicate // ------ 所谓的谓词 ------ // 条件 case.3 $where = new \Zend\Db\Sql\Where(); $expression = ...

  5. java中的访问修饰符 (2013-10-11-163 写的日志迁移

    访问级别                 修饰符                    同类                    同包              子类                 ...

  6. Scrapy-redis分布式爬虫爬取豆瓣电影详情页

    平时爬虫一般都使用Scrapy框架,通常都是在一台机器上跑,爬取速度也不能达到预期效果,数据量小,而且很容易就会被封禁IP或者账号,这时候可以使用代理IP或者登录方式爬,然而代理IP很多时候都很鸡肋, ...

  7. 初学Python不知道做什么项目好?来看看练手项目如何?

    对于初学者来说,在学习编程的初期,由于基础知识点的学习是比较无聊的,所以大家可能会有所反感,为了减弱大家的反感,我给大家带来一个简单的小项目——实现屏保计时器,这个项目就算是刚学Python的小伙伴, ...

  8. 9、python中的控制流

    学习完python的基础与数据后,我们就可以编写一些简单的命令了.但这时我们发现,目前位置写出来的程序都是自上而下顺序地执行的.要想程序改变这种自上而下的流程多一点变化,我们就要学习三种程序中的语句. ...

  9. Linux 用户行为日志记录

    工作中我们常常遇到,有的员工不安于被分配的权限,老是想sudo echo "ziji" /usr/bin/visudo NOPASSWD:ALL来进行提权,造成误删了数据库某条重要 ...

  10. [转]webservice 采用SSL实现加密传输

    本文转自:http://book.51cto.com/art/200906/129770.htm http://yeweiyun868.blog.163.com/blog/static/5637844 ...