Jackson解析toString(writeValueAsString)无响应

时间:2022-09-19 18:04:29
在学习使用Jackson时,看了 http://blog.csdn.net/gjb724332682/article/details/51586701之后就下手写了个demo
public class CountryEntity implements Serializable {
    private String code;
    private String country;
    private String letter;

    public CountryEntity() {

    }

    public CountryEntity(String code, String country) {
        this.code = code;
        this.country = country;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLetter() {
        return letter;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }
}

一开始readValue和writeValueAsString时都能正常运行,后来为了使用默认参数,加了getDefault()

public CountryEntity getDefault() {
        return new CountryEntity("86", "中国");
    }
然后writeValueAsString就一直卡着,没有耐心等待,以为是耗时就去找问题了,最后发现问题,JsonMappingException: Infinite recursion (*Error) (through reference chain),在 http://zzc1684.iteye.com/blog/2186504 中得知get/set方法会作为一种属性的方法,导致Infinite recursion,最后添加
@JsonIgnore
解决:
@JsonIgnore
    public CountryEntity getDefault() {
        return new CountryEntity("86", "中国");
    }
要细心,认真看反馈。