无法编写JSON通用对象

时间:2015-03-25 19:26:00

标签: java ajax json spring-mvc

当我尝试返回一个通用对象时,我得到了一个例外:

@RequestMapping(value="/administration/get_stat_all") 
public @ResponseBody
List<StatAllBean<String>>  get_stat_all(..) {

List<StatAllBean<String>> all_stats = new ArrayList<StatAllBean<String>>();
....
return all_stats ;

这是我的目标:

public class StatAllBean<T> {

    public Map<T, Long> totalMap ;
    public Date date;

例外:

19:14:56.366 [http-nio-8080-exec-9] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [<java.lang.reflect.MalformedParameterizedTypeException>]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]); nested exception is org.codehaus.jackson.map.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0])

3 个答案:

答案 0 :(得分:1)

all_stats列表是一个空列表,您需要检查:

return ( all_stats.isEmpty() ? null : all_stats );

答案 1 :(得分:0)

这是一个很大的提示&#34;无法编写JSON :(是java.lang.NullPointerException&#34;

看起来像你传递的东西是null。您是否正在初始化地图变量&#39; totalMap&#39;在使用之前?

答案 2 :(得分:0)

答案是here所以我编辑我的对象:

public class StatAllBean<T> {

    public Map<T, Long> totalMap ;
    public Date date;


    @JsonCreator
    public StatAllBean(Date date , @JsonProperty("totalMap")  Map<T, Long> totalMap){
        this.date = date;
        this.totalMap = totalMap;

    }
    ...