JSON序列化异常:JsonMappingException:指定的映射为空

时间:2013-07-01 09:45:06

标签: java json annotations jackson

如何解决JSON序列化异常:JsonMappingException:指定的地图是空的?

我正在使用Jackson来序列化具有List类型属性的对象。 如果列表不为空,它工作正常。但是当列表为空时我得到以下异常

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Specified map is empty (through reference chain: com.stanley.value.PageableResult["elements"]->java.util.ArrayList[0]); 
nested exception is org.codehaus.jackson.map.JsonMappingException: Specified map is empty (through reference chain: com.stanley.value.PageableResult["elements"]->java.util.ArrayList[0])

我尝试添加以下注释,但我仍然收到错误

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)

以下是PageableResult

的源代码
package com.stanley.value;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
public class PageableResult<T> {
    private List<T> elements = new ArrayList<T>();
    private int page;
    private int totalPage;
    private long totalElement;

    public List<T> getElements() {
        return elements;
    }

    public void setElements(List<T> elements) {
        this.elements = elements;
    }

    @JsonIgnore
    public int getSize() {
        if (this.elements != null) {
            return this.elements.size();
        }
        return 0;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public boolean hasNextPage() {
        return this.page < this.totalPage;
    }

    public boolean hasPreviousPage() {
        return this.page > 1;
    }

    public long getTotalElement() {
        return totalElement;
    }

    public void setTotalElement(long totalElement) {
        this.totalElement = totalElement;
    }
}

我该怎么做才能解决错误?

0 个答案:

没有答案