欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

JsonMappingException: (was java.lang.NullPointerException)

发布时间:2024/4/13 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 JsonMappingException: (was java.lang.NullPointerException) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

使用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;} }


测试方法:

@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();}}

 原因: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

转载于:https://blog.51cto.com/huangkunlun520/1711398

总结

以上是生活随笔为你收集整理的JsonMappingException: (was java.lang.NullPointerException)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。