gpt4 book ai didi

java - 使用 Jackson 反序列化枚举字段

转载 作者:行者123 更新时间:2023-11-30 06:41:52 25 4
gpt4 key购买 nike

我有一个简单的枚举 Days

public enum Days {
@JsonProperty("Monday")
MONDAY("Monday"),
@JsonProperty("Tuesday")
TUESDAY("Tuesday");

private String day;

Days(String day) {
this.day = day;
}

@JsonValue
public String getDay() {
return day;
}
}

和一个类Event

public class Event {
private Days day;
private String name;


@JsonCreator
public Event(@JsonProperty("day") Days day,
@JsonProperty("name") String name) {
this.day = day;
this.name = name;
}

public Days getDay() {
return day;
}

public String getName() {
return name;
}
}

我正在使用 Jackson 2.9,this answer 表示使用 @JsonProperty 应该足够了,但是我很难反序列化它:

public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Event event = new Event(Days.MONDAY, "Birthday");

String serialisedEvent = objectMapper.writeValueAsString(event);
System.out.println(serialisedEvent);
// {"day":"Monday","name":"Birthday"}

Event deserialisedEvent = objectMapper.convertValue(serialisedEvent, Event.class);
// Exception in thread "main" java.lang.IllegalArgumentException: Cannot construct instance of `xyz.blabla.Event` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"day":"Monday","name":"Birthday"}')
// at [Source: UNKNOWN; line: -1, column: -1]
// at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3750)
System.out.println(deserialisedEvent.getDay());
}

我在 Spring Boot 2 项目中使用 Java 11 和 Jackson 2.9。我怎样才能使它工作?

最佳答案

Jackson反序列化方法叫做readValue

convertValue 的目的不同——它首先序列化一个对象(它可能是一个字符串——它会变成一个 JSON-string-literal),然后将结果反序列化为目标类型的对象。

以下应该有效:

Event deserialisedEvent = objectMapper.readValue(serialisedEvent, Event.class);

关于java - 使用 Jackson 反序列化枚举字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503281/

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