gpt4 book ai didi

android - @IntDef Android 支持带有 Jackson 反序列化的注释

转载 作者:IT老高 更新时间:2023-10-28 23:01:02 27 4
gpt4 key购买 nike

将 JacksonAnnotations 与 Android 支持注释一起使用。我的 POJO 是:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Schedule {
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;

private Integer weekday;

public Schedule() {
}

@Weekday
public Integer getWeekday() {
return weekday;
}

public void setWeekday(@Weekday Integer weekday) {
this.weekday = weekday;
}

@Retention(RetentionPolicy.RUNTIME)
@IntDef({SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY})
public @interface Weekday {}
}

从支持我得到对象:

{"schedule":{"weekday":"MONDAY"}}

我想要的是将 Weekday 映射到常量中定义的整数值。有什么办法可以做到这一点?

更新:主要目的是优化(你应该严格避免在Android上使用枚举就像它所说的here)。

最佳答案

由于您可以指望工作日不会失控,因此创建静态 map 似乎是一个非常干净的解决方案。提供一个名为 fromString@JsonCreator 工厂可以与 Jackson 一起使用,也可以 play nicely with JAX-RS :

public class Schedule {
...
private static final ImmutableMap<String, Schedule> WEEKDAY_TO_INT_MAP =
ImmutableMap.<String, Schedule>builder()
.put("SUNDAY", withIntWeekday(0))
.put("MONDAY", withIntWeekday(1))
.put("TUESDAY", withIntWeekday(2))
.put("WEDNESDAY", withIntWeekday(3))
.put("THURSDAY", withIntWeekday(4))
.put("FRIDAY", withIntWeekday(5))
.put("SATURDAY", withIntWeekday(6))
.build();

public static Schedule withIntWeekday(int weekdayInt) {
Schedule schedule = new Schedule();
schedule.setWeekday(weekdayInt);
return schedule;
}

@JsonCreator
public static Schedule fromString(String weekday) {
return WEEKDAY_TO_INT_MAP.get(weekday);
}
...
}

关于android - @IntDef Android 支持带有 Jackson 反序列化的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31134030/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com