I have been taking advantage of Jackson JSON parser to map out my objects. While testing out the api, I have come across an issue with creating/updating my object that includes nested objects.
Creating and Updating main object
Airplane plane = airplanes.get(planeId);
if(plane == null){
plane = mapper.readValue(jsonNode, Airplane.class)
}else{
mapper.readerForUpdating(plane).readValue(jsonNode);
}
Example of objects:
public class Airplane {
private static final String TAG = "Airplane Model";
@JsonProperty("id")
private String mId;
@JsonProperty("company")
private String mCompany;
@JsonProperty("pilot")
private Pilot mPilot;
@JsonProperty("passenger")
private Passenger mPassenger;
public Airplane() {
}
}
public class Pilot {
private static final String TAG = "Pilot Model";
@JsonProperty("id")
private String mId;
@JsonProperty("name")
private String mName;
public Pilot() {
//keeps getting called on airplane reader update
}
}
Everything maps correctly, however the issue is that every time an airplane object is updated, it creates a new nested object of 'Pilot' as commented in the Pilot() constructor. This becomes a larger issue because the airplane model is being updated by a web socket at a small time interval (Unnecessary object instantiation). Additionally, I am setting non-mapped fields in the Pilot object which are being lost due to a new Pilot object being created on every update.
What is the proper way to update an object via Jackson with nested objects? Am I missing any annotations to prevent repetitive instantiation of my nested objects.
need to add @JsonMerge annotation on the mPilot field. That will instruct jackson to do deep copy, and the pilot's fields will be updated correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With