3

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.

MartyIX
  • 27,828
  • 29
  • 136
  • 207
shug
  • 134
  • 1
  • 6
  • the answers to this SO question will help... http://stackoverflow.com/questions/9895041/merging-two-json-documents-using-jackson – Hector Mar 09 '15 at 04:59

1 Answers1

0

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.

Yury
  • 89
  • 5