【问题标题】:Searialing enums as int value using @JsonProperty使用 @JsonProperty 将枚举密封为 int 值
【发布时间】:2015-10-30 13:59:15
【问题描述】:
import com.fasterxml.jackson.annotation.JsonProperty;

public enum ReviewersRating {
    @JsonProperty(0)_0,_1, _2, _3, _4, _5;  
}

我有一个需要分别转换为 int 值的枚举。如果值是String 类型,我已经成功了,但是对于int 等其他数据类型,我该怎么做?

按照其中一位 cmets 的建议,我尝试了

import com.fasterxml.jackson.annotation.JsonProperty;

public enum ReviewersRating {
    _0(0),_1(1), _2(2), _3(3), _4(4), _5(5);

    private int rating;
    private ReviewersRating(final int rating) {
        this.rating = rating;
    }

    @JsonProperty
    public int toInt()
    {
        return rating;
    }
}

结果仍未以 int 类型打印。我在 JSON "ReviewersRating": "_0",

中得到了这个

【问题讨论】:

  • 可以为每个枚举值分配一个int值,并在这个int值的getter方法上添加json注解

标签: java json enums jackson


【解决方案1】:

在 getter 方法上使用 @JsonValue 就可以了

import com.fasterxml.jackson.annotation.JsonValue;

public enum ReviewersRating {
    _0(0),_1(1), _2(2), _3(3), _4(4), _5(5);

    private final int rating;
    private ReviewersRating(final int rating) {
        this.rating = rating;
    }

    @JsonValue
    public int toInt()
    {
        return this.rating;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2011-12-30
    • 2018-10-05
    相关资源
    最近更新 更多