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

后端 未结 2 1606
广开言路
广开言路 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:49

    Can you not just add a method in value class? Note that it does not have to be either public, or use getter naming convention; you could do something like:

    public class MyStuff {
       // ... the usual fields, getters and/or setters
    
       @JsonProperty("sum") // or whatever name you need in JSON
       private int calculateSumForJSON() {
            return 42; // calculate somehow
       }
    }
    

    Otherwise you could convert POJO into JSON Tree value:

    JsonNode tree = mapper.valueToTree(value);
    

    and then modify it by adding properties etc.

提交回复
热议问题