0

如何解决 JSON 序列化异常:JsonMappingException: Specified map is empty?

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

我应该怎么做才能修复错误?

4

0 回答 0