gpt4 book ai didi

java - 解析枚举时出现 JsonMappingException

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:16 25 4
gpt4 key购买 nike

我的此类带有一个标有 @JsonCreator 的构造函数,用于将 JSON 字符串反序列化到我的类 Meal 中:

public class Meal {
private int proteins;
private int lipids;
private int carbohydrates;
private int totalKcal;
private List<Dish> dishes;
private int slot;
private MealEnum mealType;

@JsonCreator
public Meal(@JsonProperty("mealType") MealEnum mealType, @JsonProperty("dishes") List<Dish> dishes,
@JsonProperty("slot") int slot, @JsonProperty("totalKcal") int totalKcal,
@JsonProperty("carbohydrates") int carbohydrates, @JsonProperty("proteins") int proteins,
@JsonProperty("lipids") int lipids) {
this.mealType = mealType;
this.dishes = dishes;
this.slot = slot;
this.totalKcal = totalKcal;
this.carbohydrates = carbohydrates;
this.proteins = proteins;
this.lipids = lipids;
}

我还有这个枚举,其构造函数标记为@JsonCreator:

public enum MealEnum {
BREAKFAST(0, "BREAKFAST"),
LUNCH(1, "LUNCH"),
SUPPER(2, "SUPPER");
@JsonIgnore
private final int intValue;
private final String stringValue;

MealEnum(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = Objects.requireNonNull(stringValue);
}

@JsonCreator
MealEnum(@JsonProperty("mealType") String stringValue) {
this.intValue = DynamicDietistUtils.getMealEnumFromMealType(stringValue);
this.stringValue = stringValue;
}

public int getIntValue() {
return this.intValue;
}

public String getStringValue() {
return this.stringValue;
}
}

要反序列化的 JSON 如下:

{
"mealType": "BREAKFAST",
"proteins": 60,
"lipids": 147,
"carbohydrates": 461,
"totalKcal": 664,
"dishes": [{
"id": 0,
"description": "burro (10g)",
"proteins": 0.0,
"lipids": 72.0,
"carbohydrates": 0.0,
"kcal": 76
}, {
"id": 0,
"description": "pane comune (100g)",
"proteins": 32.0,
"lipids": 0.0,
"carbohydrates": 252.0,
"kcal": 290
}],
"slot": 1
}

当 Jackson 尝试反序列化 JSON 时,出现以下错误:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of mainpackage.data.model.Meal: no String-argument constructor/factory method to deserialize from String value ('mealType')

我哪里做错了?提前致谢。

最佳答案

我相信问题是在java中你不能从除了枚举值初始化列表之外的任何地方调用枚举构造函数。
因此 Jackson 无法使用枚举构造函数,您可以创建静态方法,该方法将为您从字符串中查找值。

@JsonCreator
public static MealEnum forValue(String value) {
return MaelEnum.valueOf(value); //or any other way to lookup your enum value for given string
}

关于java - 解析枚举时出现 JsonMappingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50489178/

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