杰克逊注释“JsonValue”不起作用

时间:2016-05-27 04:04:23

标签: java json jackson

我想使用apiValue(SUN,MON,...)而不是枚举值(SUNDAY,MONDAY,....)来序列化/反序列化以下枚举。我使用@JsonValue注释但它不起作用(即它使用枚举值)。知道如何解决这个问题吗?

import java.util.*;

import com.fasterxml.jackson.annotation.JsonValue;

public enum ApiNotificationScheduleDayInWeek {
        SUNDAY("SUN", 1), 
        MONDAY("MON", 2), 
        TUESDAY("TUE", 3), 
        WEDNESDAY("WED", 4), 
        THURSDAY("THU", 5), 
        FRIDAY("FRI", 6), 
        SATURDAY("SAT", 7), 
        WEEKDAY("WEEKDAY", 8),
        WEEKEND("WEEKEND", 9);
    private String apiValue;
    private Integer intValue;

    @JsonValue
    public String getApiValue() {
        return apiValue;
    }

    private ApiNotificationScheduleDayInWeek(String apiValue, Integer intValue) {
        this.apiValue = apiValue;
        this.intValue = intValue;
    }

}

1 个答案:

答案 0 :(得分:0)

你正确地进行了序列化部分,所以其他错误。由于您正在使用Jackson2注释,请确认您使用Jackson2进行序列化(而不是Jackson1或任何其他库)。还要进行一般的健全性检查,例如检查是否编译了类,部署了应用程序等等。

至于反序列化,您还需要告诉Jackson如何从API值中获取枚举实例。为此,您可以使用@JsonCreator注释静态查找方法。示例:

import com.fasterxml.jackson.annotation.JsonCreator;

@JsonCreator
public static ApiNotificationScheduleDayInWeek fromApiValue(String value) {
    if (value == null) {
        return null;
    }
    for (ApiNotificationScheduleDayInWeek day : ApiNotificationScheduleDayInWeek.values()) {
        if (value.equalsIgnoreCase(day.getApiValue())) {
            return day;
        }
    }
    throw new IllegalArgumentException("Invalid API value: " + value);
}
相关问题