简体   繁体   English

在Jackson对象映射器中自定义字段名称序列化

[英]Customizing Field Name Serialization in Jackson Object Mapper

Say I have a bean: 说我有一个豆:

public class MyBean {
    public String oneMississipi;
    public int myBestFriend;
    //Getters&Setters&Bears,Oh my.
}

And I am using com.fasterxml.Jackson DataBinding to transform instances of this pojo into json output... How do I customize the serialization of field names and can this be scoped to a global/class/field level? 而且我正在使用com.fasterxml.Jackson DataBinding将此pojo的实例转换为json输出...如何定制字段名称的序列化,并且可以将其范围设置为全局/类/字段级别?

eg I wish to dasherize my field names: 例如,我想对我的字段名称进行反斜杠:

{
    "one-mississipi": "two mississippi",
    "my-best-friend": 42
}

I have already spent hours in Google and even trawling through the jackson code in order to find out where the field serialization occurs, but can't seem to see anywhere that it may delegate for custom field processing. 我已经在Google上花费了数小时,甚至浏览了杰克逊代码,以便找出发生字段序列化的位置,但是似乎看不到它可能委派用于自定义字段处理的任何地方。

Does anyone have any ideas as to where this functionality lies if any? 有没有人知道此功能的位置(如果有)? Much appreciated 非常感激

Implement PropertyNamingStrategy and inside the resolving methods use AnnotatedMethod , AnnotatedField or AnnotatedParameter to get the declaring class. 实现PropertyNamingStrategy并在解析方法内部使用AnnotatedMethodAnnotatedFieldAnnotatedParameter来获取声明类。 Then you can look for any custom annotation on that class and apply any custom naming depending on it. 然后,您可以在该类上查找任何自定义注释,并根据其应用任何自定义命名。

The biggest problem with this approach is that it's not possible to get the actual concrete class being serialized or deserialized, it will always return the declaring class. 这种方法最大的问题是不可能将实际的具体类进行序列化或反序列化,它将始终返回声明类。 So it won't be possible to override naming behavior in subtypes for the inherited members unless you bring them into the subtype. 因此,除非您将继承的成员带入子类型,否则将无法覆盖子成员的命名行为。

Another solution would be using different mappers for classes that have different naming strategies. 另一个解决方案是对具有不同命名策略的类使用不同的映射器。 You can make it more or less transparent by creating a top-level "router" mapper that will decide which mapper instance to use (special care must be taken for configuration methods and other non ser/deser related methods). 您可以通过创建一个顶级“路由器”映射器来使它或多或少透明,该映射器将决定要使用哪个映射器实例(必须特别注意配置方法和其他与ser / deser不相关的方法)。 Assuming that you will have a finite number of the strategies this solution should be workable too. 假设您将使用有限数量的策略,那么该解决方案也应该可行。

The drawback of this solution is that you won't be able to mix different naming strategies during a single serialization / deserialization run. 此解决方案的缺点是,您将无法在单个序列化/反序列化运行期间混合使用不同的命名策略。

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

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