我正在使用Jackson将JSON字符串反序列化为枚举。
public enum RoomType {
SHARED("shared"),
PRIVATE("private");
private String value;
RoomType(String value) {
this.value = value;
}
@JsonCreator
public static RoomType fromJson(final String jsonValue) {
for (RoomType type : values()) {
if (type.value.equals(jsonValue)) {
return type;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return value;
}
}
我想对不同的边缘情况进行单元测试:
@RunWith(JUnit4.class)
public class RoomTypeTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void fromJsonWithShared() throws Exception {
String json = "{\"roomType\":\"shared\"}";
RoomType type = mapper.readValue(json, RoomType.class);
assertThat(type).isEqualTo(RoomType.SHARED);
}
}
测试失败。调试时,我会在调用jsonValue
时看到null
为RoomType.fromJson
。看起来杰克逊没有从JSON字符串中获取值。
答案 0 :(得分:3)
我认为杰克逊并不知道传递给fromJson
方法的价值。尝试添加@JsonProperty:
@JsonCreator
public static RoomType fromJson(@JsonProperty("roomType") final String jsonValue) {
....
}