gpt4 book ai didi

Java jackson : Deserialize JSON with dynamic Names into JavaClass

转载 作者:行者123 更新时间:2023-12-04 14:51:21 24 4
gpt4 key购买 nike

我正在尝试使用 jackson 反序列化 JSON。问题是字段名称总是在变化。

这是一个示例 JSON:

{
2021-08-02: [
{
label: "OnlineGallery",
nb_uniq_visitors: 1,
nb_visits: 2,
nb_events: 2,
nb_events_with_value: 0,
sum_event_value: 0,
min_event_value: 0,
max_event_value: 0,
avg_event_value: 0,
segment: "eventCategory==OnlineGallery",
idsubdatatable: 1
}
],
2021-08-03: [ ],
2021-08-04: [ ]
}

我通过 Resttemplate 获取数据并尝试反序列化为 Java 类,但它不起作用:

private EventsGetCategory getEventFromAPI(Date startdate, Date enddate) {
RestTemplate restTemplate = new RestTemplate();

DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

ResponseEntity<EventsGetCategory> response =
restTemplate.getForEntity(
matomoUrl + "index.php?module=API&label=OnlineGallery&method=Events.getCategory&secondaryDimension=eventAction&idSite=1&period=day&date=" + dateFormat.format(startdate) + "," + dateFormat.format(enddate) + "&format=JSON&filter_limit=-1"
+ "&token_auth=" + tokenAuth,
EventsGetCategory.class);

return response.getBody();
}

EventsGetCategory 类:

@Data
public class EventsGetCategory {

@JsonAnySetter
private Map<String, List<EventDetails>> details;

}

事件详情类:

@Data
public class EventDetails {

String label;
int nb_uniq_visitors;
int nb_visits;
int nb_events;
int nb_events_with_value;
int sum_event_value;
int min_event_value;
int max_event_value;
int avg_event_value;
String segment;
int idsubdatatable;

}

有人可以帮帮我吗?

最佳答案

像这样更新您的 EventsGetCategory

public class EventsGetCategory {
private Map<String, List<EventDetails>> details;

@JsonAnySetter
public void setDetails(String key, List<EventDetails> val) {
if (this.details == null) {
this.details = new HashMap<>();
}
this.details.put(key, val);
}
}

关于Java jackson : Deserialize JSON with dynamic Names into JavaClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69040354/

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