78

我正在为我的应用程序开发一个 REST 接口,使用 Jackson 将我的 POJO 域对象序列化为 JSON 表示。我想为某些类型自定义序列化,以向 POJO 中不存在的 JSON 表示添加额外的属性(例如添加一些元数据、参考数据等)。我知道如何编写我自己的,但在这种情况下,我需要为我的对象的每个JsonSerializer属性显式调用JsonGenerator.writeXXX(..)方法,而我只需要添加一个附加属性。换句话说,我希望能够写出类似的东西:

@Override
public void serialize(TaxonomyNode value, JsonGenerator jgen, SerializerProvider provider) {
    jgen.writeStartObject();
    jgen.writeAllFields(value); // <-- The method I'd like to have
    jgen.writeObjectField("my_extra_field", "some data");
    jgen.writeEndObject();
}

或者(甚至更好)以某种方式在jgen.writeEndObject()调用之前拦截序列化,例如:

@Override void beforeEndObject(....) {
    jgen.writeObjectField("my_extra_field", "some data");
}

我以为我可以扩展BeanSerializer和覆盖它的serialize(..)方法,但是它被声明了final,而且我找不到一种简单的方法来创建一个新实例,BeanSerializer而不提供所有类型元数据细节,实际上复制了 Jackson 的很大一部分。所以我已经放弃这样做了。

我的问题是- 如何自定义 Jackson 的序列化以向特定 POJO 的 JSON 输出添加额外的内容,而不引入过多的样板代码并尽可能多地重用默认的 Jackson 行为。

4

11 回答 11

43

Jackson 2.5 引入了@JsonAppend注解,可用于在序列化过程中添加“虚拟”属性。它可以与 mixin 功能一起使用,以避免修改原始 POJO。

以下示例ApprovalState在序列化期间添加了一个属性:

@JsonAppend(
    attrs = {
        @JsonAppend.Attr(value = "ApprovalState")
    }
)
public static class ApprovalMixin {}

使用以下命令注册 mixin ObjectMapper

mapper.addMixIn(POJO.class, ApprovalMixin.class);

在序列化过程中使用 anObjectWriter设置属性:

ObjectWriter writer = mapper.writerFor(POJO.class)
                          .withAttribute("ApprovalState", "Pending");

使用编写器进行序列化会将ApprovalState字段添加到输出中。

于 2017-02-25T11:22:12.457 回答
37

从(我认为)杰克逊 1.7 开始,您可以使用 aBeanSerializerModifier和扩展来做到这一点BeanSerializerBase。我已经用 Jackson 2.0.4 测试了下面的例子。

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;


public class JacksonSerializeWithExtraField {

    @Test
    public void testAddExtraField() throws Exception
    {
        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new SimpleModule() {

            public void setupModule(SetupContext context) {
                super.setupModule(context);

                context.addBeanSerializerModifier(new BeanSerializerModifier() {

                    public JsonSerializer<?> modifySerializer(
                            SerializationConfig config,
                            BeanDescription beanDesc,
                            JsonSerializer<?> serializer) {
                        if (serializer instanceof BeanSerializerBase) { 
                              return new ExtraFieldSerializer(
                                   (BeanSerializerBase) serializer);
                        } 
                        return serializer; 

                    }                   
                });
            }           
        });

        mapper.writeValue(System.out, new MyClass());       
        //prints {"classField":"classFieldValue","extraField":"extraFieldValue"}
    }


    class MyClass {

        private String classField = "classFieldValue";

        public String getClassField() { 
            return classField; 
        }
        public void setClassField(String classField) { 
            this.classField = classField; 
        }
    }


    class ExtraFieldSerializer extends BeanSerializerBase {

        ExtraFieldSerializer(BeanSerializerBase source) {
            super(source);
        }

        ExtraFieldSerializer(ExtraFieldSerializer source, 
                ObjectIdWriter objectIdWriter) {
            super(source, objectIdWriter);
        }

        ExtraFieldSerializer(ExtraFieldSerializer source, 
                String[] toIgnore) {
            super(source, toIgnore);
        }

        protected BeanSerializerBase withObjectIdWriter(
                ObjectIdWriter objectIdWriter) {
            return new ExtraFieldSerializer(this, objectIdWriter);
        }

        protected BeanSerializerBase withIgnorals(String[] toIgnore) {
            return new ExtraFieldSerializer(this, toIgnore);
        }

        public void serialize(Object bean, JsonGenerator jgen,
                SerializerProvider provider) throws IOException,
                JsonGenerationException {           
            jgen.writeStartObject();                        
            serializeFields(bean, jgen, provider);
            jgen.writeStringField("extraField", "extraFieldValue"); 
            jgen.writeEndObject();
        }
    }
}
于 2013-03-12T15:55:38.187 回答
22

您可以这样做(以前的版本在 2.6 之后无法与 Jackson 一起使用,但在 Jackson 2.7.3 中可以使用):

public static class CustomModule extends SimpleModule {
    public CustomModule() {
        addSerializer(CustomClass.class, new CustomClassSerializer());
    }

    private static class CustomClassSerializer extends JsonSerializer {
        @Override
        public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            //Validate.isInstanceOf(CustomClass.class, value);
            jgen.writeStartObject();
            JavaType javaType = provider.constructType(CustomClass.class);
            BeanDescription beanDesc = provider.getConfig().introspect(javaType);
            JsonSerializer<Object> serializer = BeanSerializerFactory.instance.findBeanSerializer(provider,
                    javaType,
                    beanDesc);
            // this is basically your 'writeAllFields()'-method:
            serializer.unwrappingSerializer(null).serialize(value, jgen, provider);
            jgen.writeObjectField("my_extra_field", "some data");
            jgen.writeEndObject();
        }
    }
}

更新:

我在 Jackson 2.9.0 和 2.9.6 上进行了尝试,两者都按预期工作。也许试试这个: http: //jdoodle.com/a/z99(在本地运行 - jdoodle 显然无法处理杰克逊)。

于 2014-08-18T09:58:49.460 回答
22

虽然这个问题已经得到解答,但我找到了另一种不需要特殊杰克逊钩子的方法。

static class JsonWrapper<T> {
    @JsonUnwrapped
    private T inner;
    private String extraField;

    public JsonWrapper(T inner, String field) {
        this.inner = inner;
        this.extraField = field;
    }

    public T getInner() {
        return inner;
    }

    public String getExtraField() {
        return extraField;
    }
}

static class BaseClass {
    private String baseField;

    public BaseClass(String baseField) {
        this.baseField = baseField;
    }

    public String getBaseField() {
        return baseField;
    }
}

public static void main(String[] args) throws JsonProcessingException {
    Object input = new JsonWrapper<>(new BaseClass("inner"), "outer");
    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(input));
}

输出:

{
  "baseField" : "inner",
  "extraField" : "outer"
}

对于编写集合,您可以简单地使用视图:

public static void main(String[] args) throws JsonProcessingException {
    List<BaseClass> inputs = Arrays.asList(new BaseClass("1"), new BaseClass("2"));
    //Google Guava Library <3
    List<JsonWrapper<BaseClass>> modInputs = Lists.transform(inputs, base -> new JsonWrapper<>(base, "hello"));
    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(modInputs));
}

输出:

[ {
  "baseField" : "1",
  "extraField" : "hello"
}, {
  "baseField" : "2",
  "extraField" : "hello"
} ]
于 2016-03-31T12:40:45.063 回答
5

另一个也许是最简单的解决方案:

使序列化成为一个两步过程。首先创建一个Map<String,Object>like:

Map<String,Object> map = req.mapper().convertValue( result, new TypeReference<Map<String,Object>>() {} );

然后添加您想要的属性:

map.put( "custom", "value" );

然后将其序列化为 json:

String json = req.mapper().writeValueAsString( map );
于 2018-02-20T12:44:18.480 回答
3

对于我的用例,我可以使用更简单的方法。在我所有的“Jackson Pojos”的基类中,我添加:

protected Map<String,Object> dynamicProperties = new HashMap<String,Object>();

...


public Object get(String name) {
    return dynamicProperties.get(name);
}

// "any getter" needed for serialization    
@JsonAnyGetter
public Map<String,Object> any() {
    return dynamicProperties;
}

@JsonAnySetter
public void set(String name, Object value) {
    dynamicProperties.put(name, value);
}

我现在可以反序列化到 Pojo,处理字段并重新序列化 witjout 丢失任何属性。我还可以添加/更改非 pojo 属性:

// Pojo fields
person.setFirstName("Annna");

// Dynamic field
person.set("ex", "test");

(从Cowtowncoder 获得

于 2018-05-16T05:30:30.060 回答
2

我们可以使用反射来获取要解析的对象的所有字段。

@JsonSerialize(using=CustomSerializer.class)
class Test{
  int id;
  String name;
  String hash;
}    

在自定义序列化程序中,我们有这样的序列化方法:

        @Override
        public void serialize(Test value, JsonGenerator jgen,
                SerializerProvider provider) throws IOException,
                JsonProcessingException {

            jgen.writeStartObject();
            Field[] fields = value.getClass().getDeclaredFields();

            for (Field field : fields) {
                try {
                    jgen.writeObjectField(field.getName(), field.get(value));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
            jgen.writeObjectField("extra_field", "whatever_value");
            jgen.writeEndObject();

        }
于 2014-10-16T11:38:10.580 回答
1

灵感来自 wajda 在此要点中所说和所写的内容:

这是在杰克逊 1.9.12 中添加 bean 序列化侦听器的方法。在此示例中,侦听器被视为命令链,其接口为:

public interface BeanSerializerListener {
    void postSerialization(Object value, JsonGenerator jgen) throws IOException;
}

MyBeanSerializer.java:

public class MyBeanSerializer extends BeanSerializerBase {
    private final BeanSerializerListener serializerListener;

    protected MyBeanSerializer(final BeanSerializerBase src, final BeanSerializerListener serializerListener) {
        super(src);
        this.serializerListener = serializerListener;
    }

    @Override
    public void serialize(final Object bean, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        if (_propertyFilterId != null) {
            serializeFieldsFiltered(bean, jgen, provider);
        } else {
            serializeFields(bean, jgen, provider);
        }

        serializerListener.postSerialization(bean, jgen);

        jgen.writeEndObject();
    }
}

MyBeanSerializerBuilder.java:

public class MyBeanSerializerBuilder extends BeanSerializerBuilder {
    private final BeanSerializerListener serializerListener;

    public MyBeanSerializerBuilder(final BasicBeanDescription beanDesc, final BeanSerializerListener serializerListener) {
        super(beanDesc);
        this.serializerListener = serializerListener;
    }

    @Override
    public JsonSerializer<?> build() {
        BeanSerializerBase src = (BeanSerializerBase) super.build();
        return new MyBeanSerializer(src, serializerListener);
    }
}

MyBeanSerializerFactory.java:

public class MyBeanSerializerFactory extends BeanSerializerFactory {

    private final BeanSerializerListener serializerListener;

    public MyBeanSerializerFactory(final BeanSerializerListener serializerListener) {
        super(null);
        this.serializerListener = serializerListener;
    }

    @Override
    protected BeanSerializerBuilder constructBeanSerializerBuilder(final BasicBeanDescription beanDesc) {
        return new MyBeanSerializerBuilder(beanDesc, serializerListener);
    }
}

下面的最后一个类显示了如何使用 Resteasy 3.0.7 提供它:

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
    private final MapperConfigurator mapperCfg;

    public ObjectMapperProvider() {
        mapperCfg = new MapperConfigurator(null, null);
        mapperCfg.setAnnotationsToUse(new Annotations[]{Annotations.JACKSON, Annotations.JAXB});
        mapperCfg.getConfiguredMapper().setSerializerFactory(serializerFactory);
    }

    @Override
    public ObjectMapper getContext(final Class<?> type) {
        return mapperCfg.getConfiguredMapper();
    }
}
于 2015-10-20T23:05:34.930 回答
1

我们可以扩展BeanSerializer,但需要一点小技巧。

首先,定义一个 java 类来包装你的 POJO。

@JsonSerialize(using = MixinResultSerializer.class)
public class MixinResult {

    private final Object origin;
    private final Map<String, String> mixed = Maps.newHashMap();

    @JsonCreator
    public MixinResult(@JsonProperty("origin") Object origin) {
        this.origin = origin;
    }

    public void add(String key, String value) {
        this.mixed.put(key, value);
    }

    public Map<String, String> getMixed() {
        return mixed;
    }

    public Object getOrigin() {
        return origin;
    }

}

然后,实现你的自定义serializer

public final class MixinResultSerializer extends BeanSerializer {

    public MixinResultSerializer() {
        super(SimpleType.construct(MixinResult.class), null, new BeanPropertyWriter[0], new BeanPropertyWriter[0]);
    }

    public MixinResultSerializer(BeanSerializerBase base) {
        super(base);
    }

    @Override
    protected void serializeFields(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (bean instanceof MixinResult) {
            MixinResult mixin  = (MixinResult) bean;
            Object      origin = mixin.getOrigin();

            BeanSerializer serializer = (BeanSerializer) provider.findValueSerializer(SimpleType.construct(origin.getClass()));

            new MixinResultSerializer(serializer).serializeFields(origin, gen, provider);

            mixin.getMixed().entrySet()
                    .stream()
                    .filter(entry -> entry.getValue() != null)
                    .forEach((entry -> {
                        try {
                            gen.writeFieldName(entry.getKey());
                            gen.writeRawValue(entry.getValue());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }));
        } else {
            super.serializeFields(bean, gen, provider);
        }

    }

}

这样,我们可以处理源对象使用杰克逊注解来自定义序列化行为的情况。

于 2016-05-06T02:11:00.323 回答
0

我也需要这种能力;就我而言,支持 REST 服务的字段扩展。我最终开发了一个小框架来解决这个问题,它在github上开源。它也可以在Maven 中央存储库中找到。

它负责所有工作。只需将 POJO 包装在一个 MorphedResult 中,然后随意添加或删除属性。序列化后,MorphedResult 包装器会消失,并且任何“更改”都会出现在序列化的 JSON 对象中。

MorphedResult<?> result = new MorphedResult<>(pojo);
result.addExpansionData("my_extra_field", "some data");

有关更多详细信息和示例,请参阅 github 页面。请务必使用 Jackson 的对象映射器注册库“过滤器”,如下所示:

ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(new FilteredResultProvider());
于 2015-03-16T21:28:36.753 回答
-1

在查看了更多关于Jackson源代码后,我得出结论,如果不编写我自己的 ,根本不可能实现BeanSerializerBeanSerializerBuilderBeanSerializerFactory提供一些扩展点,例如:

/*
/**********************************************************
/* Extension points
/**********************************************************
 */

protected void beforeEndObject(T bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JSONException {
    // May be overridden
}

protected void afterStartObject(T bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JSONException {
    // May be overridden
}

不幸的是,我不得不将整个JacksonBeanSerializer源代码复制并粘贴到,MyCustomBeanSerializer因为前者不是为将所有字段和一些重要方法(如serialize(...))声明为的扩展而开发的final

于 2013-02-07T13:28:50.560 回答