简体   繁体   中英

jackson serializer: custom serializer based on a different field

i have a field of list that i want to serialize. I also want to serialize the max of the or the max i've seen so far whenever the class is serialized.

class A {
private List<int> list;
private int max; //Math.Max(max, Collections.max(list));}

I think i need to use @JsonSerialize annotation, but the custom serializer i specify here would either take list or max, not both. Is it possible to add serializer for max field that uses data from list field?

The list is private in your class, so you completely control how elements are added to it. Ie, nothing can be added to the list without some code in your class performing the operation.

Therefore, whatever code adds (and deletes, if you do that) elements should just update the max value as part of its operation. Then when serializing use the standard serializers on both the list and the max .

If for some reason you expose the list, for example by having a method that returns a reference to the list, then you should subclass List<whatever> and override the add() method to keep track of the max.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM