I am trying to find an easy way to deserialize the following JSON to an OpeningHours Object containing a Map<String, List<String>>
which contains the days as keys and the opening hours as a list.
I am using Jackson and created my own deserializer @JsonDeserialize(using = MyDeserializer.class)
The problem is that I need to check which of the different JSON nodes is present to set the keys for the map.
Is there an easy alternative solution?
{
"OpeningHours": {
"Days": {
"Monday": {
"string": [
"09:00-13:00",
"13:30-18:00"
]
},
"Tuesday": {
"string": [
"09:00-13:00",
"13:30-18:00"
]
}
}
}
}
You could just deserialize it to a data structure that represents the JSON like
@Data
public class TempStore {
private List<DayTempStore> days;
}
@Data
public class DaytempStore {
private String[] string;
}
and just transform this to a Map> leaving the hassle with Nodes and Checks to Jackson.
Jackson can deserialize any Json into Map<String, Object>
, that may contain nested maps for nested json objects. all that is needed is casting:
String json = ...
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> openingHours = (Map<String, Object>)mapper.readValue(json, Map.class);
Map<String, List<String>> days = (Map<String, List<String>>)((Map<String, Object>)openingHours.get("OpeningHours")).get("Days");
System.out.println(days);
output:
{Monday={string=[09:00-13:00, 13:30-18:00]}, Tuesday={string=[09:00-13:00, 13:30-18:00]}}
I think you are making the issue is a bit more complex than it is. You don't need a custom deserializer in this case. All you need is this:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModules(new JavaTimeModule());
ObjectReader obrecjReader = objectMapper.reader();
Map<String, Object> myMap = objectReader.forType(Map<String,Object>.class).readValue(jsonString);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.