JsonMappingException: (was java. lang. NullPointerException)
An exception is reported when java objects are serialized using jackson:
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
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 () {}/ ***** display name of the number of users */public String name; /***** free storage space for each user */public Integer age; public String getName () {return name;} public int getAge () {return age ;}}
Test method:
@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(); } }
Cause: the age attribute of the member variable in the Student class is Integer (packaging type), but in the corresponding getter method, the returned value is of the basic type int. solution: Method 1: Modify the getter method, and change the returned value to the packaging type Integer. Method 2: Modify the getter method:
public int getAge() { if(age==null){ return 0; } return age;}