英文:
Map a dynamic json key to a class field using JPA
问题
我正在尝试将一个 JSON 对象映射到一个实体类(Entity class)。我的 JSON 如下所示:
{
"availabilities": {
"2020-07-14T00:00:00Z": "Not Available",
"2020-08-14T00:00:00Z": "Not Available",
"2020-06-14T00:00:00Z": "Not Available",
"2020-05-14T00:00:00Z": "Not Available",
"2020-00-14T00:00:00Z": "Not Available"
}
}
我使用 Spring Data 创建了一个实体类:
@Entity
public class Availabilities {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String date;
private String availability;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAvailability() {
return availability;
}
public void setAvailability(String availability) {
this.availability = availability;
}
}
但我得到了以下错误:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "2020-07-14T00:00:00Z" (class org.abc.hotel.booking.model.Availabilities)
请帮助。
英文:
I am trying to map a json object to an Entity class. My Json is as follows:
{
"availabilities": {
"2020-07-14T00:00:00Z": "Not Available",
"2020-08-14T00:00:00Z": "Not Available",
"2020-06-14T00:00:00Z": "Not Available",
"2020-05-14T00:00:00Z": "Not Available",
"2020-00-14T00:00:00Z": "Not Available"
}
}
I created a entity class using spring data :
@Entity
public class Availabilities {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String date;
private String availibility;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAvailibility() {
return availibility;
}
public void setAvailibility(String availibility) {
this.availibility = availibility;
}
}
But i am getting the following error:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "2020-
07-14T00:00:00Z" (class org.abc.hotel.booking.model.Availabilities)
Please help.
答案1
得分: 1
你的代码正在尝试按键值映射,这意味着你的变量是键。在你的情况下,JSON 应该如下工作:
// 映射到可用性
{
"date": "2020-07-14T00:00:00Z",
"availibility": "Not Available"
}
如果你想解析成列表 => https://stackoverflow.com/questions/44589381/how-to-convert-json-string-into-list-of-java-object
英文:
your code is trying map by key-value, that mean your variable is the key.
in your case. json look like this will work
// map to Availabilities
{
"date": "2020-07-14T00:00:00Z",
"availibility": "Not Available",
}
if you want to parse into a list => https://stackoverflow.com/questions/44589381/how-to-convert-json-string-into-list-of-java-object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论