Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Parser: Updating a mapped object with nested objects

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.

like image 914
shug Avatar asked Feb 26 '26 01:02

shug


1 Answers

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.

like image 153
Yury Avatar answered Feb 28 '26 14:02

Yury



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!