使用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;
- @ModelAttribute("name")
- public String getName() {
- return name;
- }
- @ModelAttribute("age")
- 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方法为:
- @ModelAttribute("age")
- public int getAge() {
- if(age==null){
- return 0;
- }
- return age;
- }
参考:http://www.cnblogs.com/jimmy-c/p/3978799.html
时间: 2024-10-31 10:10:39