Reputation: 33
I'm trying to deserialize JSON using jackson. The problem is that field names always change.
Here is an example 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: [ ]
}
I´m getting the data by Resttemplate and try to deserialize into Java Class but it doesn't work:
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 Class:
@Data
public class EventsGetCategory {
@JsonAnySetter
private Map<String, List<EventDetails>> details;
}
EventDetails Class:
@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;
}
Can someone help me please?
Upvotes: 3
Views: 595
Reputation: 1670
Update Your EventsGetCategory
class like this
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);
}
}
Upvotes: 1
Reputation: 56
if the field names are always changed then you can not use a class like EventDetails to map the JSON object to a java class, instead of EventDetails class, you have to use Map<String, Object> where you can store dynamic key values.
Upvotes: 1