【发布时间】:2018-05-23 13:03:28
【问题描述】:
我有一个带有标记为@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')
我哪里做错了? 提前致谢。
【问题讨论】: