report exception when using Jackson to serialize Java objects :
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
The serialized class :
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 () {}/*** * Number of users display name */public String name;/*** * Free storage space per user */public Integer age;public strin G GetName () {return name;} public int getage () {return age;}}
Test method:
@Testpublic 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 ()}}
Cause: The attribute of the member variable age in the Student class is an Integer (wrapper type), but in the corresponding getter method, the primitive type int is returned.
Workaround :
Method One: Modify Getter method, return value to wrapper type integer
Way two:
To modify the Getter method:
public int Getage () {if (age==null) {return 0;} return age;}
Reference: http://www.cnblogs.com/jimmy-c/p/3978799.html
http://hw1287789687.iteye.com/blog/2255940
This article is from the "Whuang" blog, make sure to keep this source http://huangkunlun520.blog.51cto.com/2562772/1711398
Jsonmappingexception: (Was java.lang.NullPointerException)