'Custom jackson deserializer only for nested class
I have a vehicle Java class defined like this:
public final class Vehicle {
private Integer id;
private String description;
private Location start;
private Location end;
private List<Integer> capacity;
private List<Integer> skills;
private TimeWindow timeWindow;
private List<Break> breaks;
public Vehicle(Integer id, String description, Location start,
Location end, List<Integer> capacity,
List<Integer> skills, TimeWindow timeWindow,
List<Break> breaks) {
this.id = id;
this.description = description;
this.start = start;
this.end = end;
this.capacity = capacity;
this.skills = skills;
this.timeWindow = timeWindow;
this.breaks = breaks;
}
TimeWindow is defined like this:
public final class Location {
private final Double latitude;
private final Double longitude;
public Location(Double latitude, Double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
Now, the JSON I am getting, does not define latitude and longitude for the location (start and end); this information is encoded as just an array, see e.g.:
// vehicle.json
{
"id" : 0,
"description" : "vehicle 0",
"start" : [
12.304373066846503,
51.62270653765847
],
"end" : [
12.304373066846503,
51.62270653765847
],
"capacity" : [
9
],
"skills" : [
],
"time_window" : [
1644188400,
1644274800
],
"breaks" : [
]
}
How can I write a custom deserializer for just Location (same problem with TimeWindow) in that case? If possible, I do not want to write a custom deserializer for the whole Vehicle class.
I tried this:
@JsonDeserialize(
using = LocationJsonDeserializer.class
)
public final class Location {
// ....
public class LocationJsonDeserializer extends JsonDeserializer<Location> {
@Override
public Location deserialize(JsonParser p, DeserializationContext ctxt) {
final var longitude = 0d;
final var latitude = 0d;
// what to do here?
return new Location(latitude, longitude);
}
It seems to me, that I am getting the whole Vehicle passed into my deserialize method, not just the Location part. Am I doing something wrong here? Is this approach feasible using Jackson?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
