杰克逊:如何在不修改POJO的情况下向JSON添加自定义属性

时间:2013-02-05 18:28:10

标签: java json serialization jackson customization

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

@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,而且我找不到一种简单的方法来创建{{1}的新实例没有提供所有类型的元数据细节实际上复制了杰克逊的一部分。所以我已经放弃了这样做。

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

11 个答案:

答案 0 :(得分:37)

从(我认为)杰克逊1.7开始,您可以使用BeanSerializerModifier并扩展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();
        }
    }
}

答案 1 :(得分:23)

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

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

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

使用ObjectMapper注册mixin:

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

使用ObjectWriter在序列化期间设置属性:

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

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

答案 2 :(得分:15)

你可以这样做(以前的版本在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();
        }
    }
}

答案 3 :(得分:13)

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

{
  "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"
} ]

输出:

{{1}}

答案 4 :(得分:3)

对于我的用例,我可以使用更简单的方法。在我所有的&#34; Jackson Pojos&#34;我补充说:

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,使用字段并且可能会失去任何属性。我还可以添加/更改非pojo属性:

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

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

(来自Cowtowncoder

答案 5 :(得分: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();

        }

答案 6 :(得分:2)

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

使序列化分为两个步骤。首先创建一个Map<String,Object>,如:

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

然后添加您想要的属性:

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

然后将其序列化为json:

String json = req.mapper().writeValueAsString( map );

答案 7 :(得分:1)

受到wajda在gist中所说和写的启发:

以下是如何在jackson 1.9.12中为bean序列化添加监听器。在此示例中,listerner被视为命令链,其接口为:

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();
    }
}

答案 8 :(得分: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);
        }

    }

}

这样,我们可以使用jackson注释处理原始对象的情况,以自定义序列化行为。

答案 9 :(得分:0)

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

它负责所有的工作。只需将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());

答案 10 :(得分:-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
}

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