How to add extra fields to an Object during Jackson's json serialization?

后端 未结 2 1607
广开言路
广开言路 2021-01-17 10:49

I need to add new property to an object, when serializing to JSON. The value for the property is calculated on runtime and does not exist in the object. Also the same object

2条回答
  •  粉色の甜心
    2021-01-17 11:39

    One option is to add a field for this property and set it on the object before writing to JSON. A second option, if the property can be computed from other object properties you could just add a getter for it, for example:

    public String getFullName() {
      return getFirstName() + " " + getLastName();
    }
    

    And even though there's no matching field Jackson will automatically call this getter while writing the JSON and it will appear as fullName in the JSON output. If that won't work a third option is to convert the object to a map and then manipulate it however you need:

    ObjectMapper mapper //.....
    MyObject o //.....
    long specialValue //.....
    Map map = mapper.convertValue(o, new TypeReference>() { });
    map.put("specialValue", specialValue);
    

    You're question didn't mention unmarshalling but if you need to do that as well then the first option would work fine but the second two would need some tweaking.

    And as for writing different fields of the same object it sounds like a job for @JsonView

提交回复
热议问题