标签:jackson 序列化 反序列化 jsonmappingexception
使用jackson 序列化java对象的时候报异常:
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.chanjet.gov.Student["age"]) at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:218) at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:183) at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:155) at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:512) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:117) at
被序列化的类:
package com.chanjet.gov; import org.springframework.web.bind.annotation.ModelAttribute; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; /** * Created by JasonQin on 2015/7/1. */ @JsonAutoDetect @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class Student { public Student() { } /*** * 用户数显示名称 */ public String name; /*** * 每用户的免费存储空间 */ public Integer age; public String getName() { return name; } public int getAge() { return age; } }
测试方法:
@Test public void test_PolicyInfo(){ ObjectMapper mapper = new ObjectMapper(); Student s=new Student(); try { System.out.println(mapper.writeValueAsString(s)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
原因:Student 类中成员变量age的属性是Integer(包装类型),但是在对应的getter方法中,返回的却是基本类型int.
解决方法:
方式一:修改getter方法,返回值改为包装类型Integer
方式二:
修改getter方法为:
public int getAge() { if(age==null){ return 0; } return age; }
参考:http://www.cnblogs.com/jimmy-c/p/3978799.html
http://hw1287789687.iteye.com/blog/2255940
本文出自 “whuang” 博客,请务必保留此出处http://huangkunlun520.blog.51cto.com/2562772/1711398
JsonMappingException: (was java.lang.NullPointerException)
标签:jackson 序列化 反序列化 jsonmappingexception
原文地址:http://huangkunlun520.blog.51cto.com/2562772/1711398