如何在自定义json序列化程序中获取属性或字段名称 [英] how to get property or field name in a custom json serializer

查看:2201
本文介绍了如何在自定义json序列化程序中获取属性或字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义JsonSerializer 对于字段(简化代码):

I have a custom JsonSerializer for a field (simplified code):

@JsonSerialize(using=Text1Serializer.class)
@JsonProperty("text1") // I need this inside the custom serializer
@Override
public String getTextOne() {
    return "foo";
}

// ...

public static class Text1Serializerextends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        // how to get "text1" here?
        provider.defaultSerializeValue(value, jgen);
    }

}

因为我需要序列化大约十具有类似逻辑的其他字段,仅取决于字段 name ,如果我可以在自定义序列化程序中获取属性名称,它将非常有用 - 而不是编写十个相同的序列化程序。

Since I need to serialize about ten other fields with a similar logic, that just depends on the field name, it would help me very much if I could get the property name inside the custom serializer - instead of writing ten identical serializers.

我在 serialize()方法中看到我可以用 JsonGenerator获取整个对象.getCurrentValue()(请参阅此答案),但我没有找到办法获得字段名称。

I've seen that inside the serialize() method I can get the whole object with JsonGenerator.getCurrentValue() (see this answer), but I didnt' find a way to get the field name.

我正在使用Jackson 2.6

I'm using Jackson 2.6

推荐答案

如果您实现了ContextualSerializer,这将用于生成序列化程序的上下文版本,即使用BeanProperty配置的版本:

If you implement ContextualSerializer, this will be used to produce a "contextual" version of your serializer, i.e. one that is configured using the BeanProperty:

public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
    throws JsonMappingException;

这应该返回为给定属性定制的新实例:它不必是与非自定义序列化程序相同的类(尽管标准的Jackson实现似乎都以这种方式工作)。

This should return a new instance that is customised for the given property: it doesn't have to be the same class as the non-customised serializer (although the standard Jackson implementations all seem to work that way).

这篇关于如何在自定义json序列化程序中获取属性或字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆