gpt4 book ai didi

java - 如何通过读取 JSON 来修复 UnrecognizedPropertyException?

转载 作者:行者123 更新时间:2023-12-02 09:04:38 25 4
gpt4 key购买 nike

我有一个实体类:

@Entity
@Table(name = "meals")
public class Meal extends AbstractNamedEntity implements Serializable {
private static final long serialVersionUID = 1L;

@NotNull(message = "Price must be added")
private Integer price;

@JsonIgnore
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date = LocalDate.now();

@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "restaurant_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Restaurant restaurant;

public Meal() {
}
//getters and setters
}

当我使用测试数据测试我的 Controller 时:

public class MealTestData {
private static final Integer START_SEQ = 100000;

public static final Meal MEAL_1 = new Meal(START_SEQ + 6, "ChickenBurger set", 300, RESTAURANT_1);
public static final Meal MEAL_2 = new Meal(START_SEQ + 7, "CheeseBurger set", 400, RESTAURANT_1);
public static final Meal MEAL_3 = new Meal(START_SEQ + 8, "FishBurger set", 500, RESTAURANT_1);
}

我得到这个异常:

java.lang.IllegalArgumentException: Invalid read array from JSON: '[{"id":100006,"name":"ChickenBurger set","price":300,"date":"2020-01-26"},{"id":100007,"name":"CheeseBurger set","price":400,"date":"2020-01-26"},{"id":100008,"name":"FishBurger set","price":500,"date":"2020-01-26"}]';

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "date" (class ru.topjava.graduation.model.Meal), not marked as ignorable (3 known properties: "price", "id", "name"]) at [Source: (String)"[{"id":100006,"name":"ChickenBurger set","price":300,"date":"2020-01-26"},{"id":100007,"name":"CheeseBurger set","price":400,"date":"2020-01-26"},{"id":100008,"name":"FishBurger set","price":500,"date":"2020-01-26"}]"; line: 1, column: 62] (through reference chain: ru.topjava.graduation.model.Meal["date"])

是什么原因以及如何解决?我不能在测试中忽略该字段

提供了“日期”字段的 getter 和 setter:

public LocalDate getDate() {
return date;
}

public void setDate(LocalDate date) {
this.date = date;
}

最佳答案

您在“日期”字段上有 @JsonIgnore 注释:

@JsonIgnore
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date = LocalDate.now();

但该字段存在于输入 json 中:

{"id":100006,"name":"ChickenBurger set","price":300,"date":"2020-01-26"},

因此,要么删除默认值生成,要么切换 ObjectMapper 的设置,如下所示:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

关于java - 如何通过读取 JSON 来修复 UnrecognizedPropertyException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59913490/

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