简体   繁体   English

杰克逊序列化器:基于不同字段的自定义序列化器

[英]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. 我认为我需要使用@JsonSerialize批注,但我在此处指定的自定义序列化程序将采用列表或最大值,而不是两者都采用。 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. 该列表在您的课程中是private ,因此您可以完全控制如何向其中添加元素。 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. 因此,无论代码添加(或删除,如果这样做)元素,都应仅在操作中更新max Then when serializing use the standard serializers on both the list and the max . 然后在序列化时,使用列表和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. 如果出于某种原因(例如,通过具有返回对列表的引用的方法)来公开列表,则应将List<whatever>子类化,并重写add()方法以跟踪最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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