自定义或动态 @JsonProperty 适用于所有字段,无需使用 Jackson 进行注释
我正在寻找一种方法来自定义杰克逊的序列化键和反序列化设置器调用。我有几百个对象,它们都以某种方式与不同级别的抽象和接口相关,但是它们没有很多继承的字段。我正在使用适用于所有类的 mixin 来利用过滤器和 TypeIdResolver。我想要序列化为 json 的所有字段都以“attribute”结尾,但我不希望 json 中的每个键后面都有属性。我无法重构字段和方法名称,因为它用于遗留 XML 解析,而且我无法破坏它。我真的不想将 @JsonProperty 添加到每个字段;我正在寻找更有活力的东西。某种方法可以检查要序列化的字段或要反序列化的键并根据我的喜好进行修改。
对于反序列化,我想我也许可以使用 InjectibleValues,但我没有尝试过,因为我无法找到任何东西来自定义输出键。
例如,
String nameAttribute = "xyz";
getNameAttribute()
"name"="xyz"
不
"nameAttribute"="xyz"
I'm looking for a way to customize the serialized keys and deserialized setter calls for jackson. I have a few hundred objects that are all somehow related with various levels of abstractions and interfaces, however they don't have many inherited fields. I am using a mixin that applies to all my classes to utilize a filter and a TypeIdResolver. All of the fields I want serialized to json end in 'attribute', but I don't want attribute after every key in the json. I'm unable to refactor the field and method names as it's used for legacy XML parsing and I can't break that. I really don't want to add @JsonProperty to every field; I'm looking for something more dynamic. Some way to inspect fields to serialize or keys to deserialize and modify it to my liking.
For deserialization, I think I might be able to use InjectibleValues, but I haven't tried as I haven't been able to find anything to customize the output keys.
for example,
String nameAttribute = "xyz";
getNameAttribute()
"name"="xyz"
Not
"nameAttribute"="xyz"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够使用 JacksonAnnotationIntrospector 的自定义扩展来解决这个问题。我重写了查找 @JsonProperty 的方法并提供了我自己的逻辑。我还必须实现我自己的 hasIgnoreMarker() 以避免将 @JsonIgnore 到处乱放,因为直到实际序列化时才会发生过滤,因此我收到了有关重复 getter 和 setter 的错误。
I was able to solve this with a custom extension of JacksonAnnotationIntrospector. I overrode the methods that look for @JsonProperty and provided my own logic. I also had to implement my own hasIgnoreMarker() to avoid placing @JsonIgnore all over the place because the filtering doesn't happen until the actual serialization so I was getting errors about duplicate getters and setters.