@JsonSerialize-如何在运行时创建包装器并为对象字段使用默认序列化? [英] @JsonSerialize - How to create a wrapper at runtime and use default serialization for the object fields?

查看:162
本文介绍了@JsonSerialize-如何在运行时创建包装器并为对象字段使用默认序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个在运行时确定名称的包装器,因为它取决于类名(我可以使用@JsonRootName,但我不想这样做,因为我必须在每个子类中使用它,这是效率不高).

I want to add a wrapper which named is determined at runtime, because it depends of the class name (I could use @JsonRootName but I don't want to because I would have to use it on every sub class, which is not efficient).

我想我应该使用@JsonSerialize覆盖默认的序列化器,但是我只想创建包装器;我不想自己序列化对象字段(我也处于抽象类中,所以我什至不知道子类的字段!).我不在乎它们,我只是在乎包装器!因此,我希望默认的序列化程序可以为我或类似的人处理这些字段.

I suppose I should use @JsonSerialize to override the default serializer, but I want that just to create the wrapper; I don't want to serialize the object fields myself (also I am in an abstract class, so I don't even know the fields of the sub class!). I don't care about them, I just care about the wrapper! So I would like the default serializer to handle those fields for me, or something like that.

@JsonSerialize(using = CustomSerializer.class)
public abstract class Request {

    public static class CustomSerializer extends JsonSerializer<Request > {
        @Override
        public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            // Doing my stuff to determine the wrapper name based on request.class.getSimpleName()
            // Then what should I wright to serialize the fields?
            // Basically I just want a function to generate the same json that the default serializer would generate!

            // I tried the following, but obviously it gives a com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion
            jgen.writeObject(value);

            // Same error for the function below 
            provider.defaultSerializeValue(value, jgen);
        }
    }

推荐答案

要创建包装器序列化程序,您需要使用com.fasterxml.jackson.databind.ser.BeanSerializerModifier类.您可以使用com.fasterxml.jackson.databind.module.SimpleModule注册它.下面的示例显示了端到端解决方案的实现方法:

To create wrapper serialiser you need to use com.fasterxml.jackson.databind.ser.BeanSerializerModifier class. You can register it using com.fasterxml.jackson.databind.module.SimpleModule. Below example shows end-to-end solution how to do that:

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.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.util.NameTransformer;

import java.io.IOException;
import java.util.UUID;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        SimpleModule wrappersModule = new SimpleModule("requestWrapper");
        wrappersModule.setSerializerModifier(new BeanSerializerModifier() {
            @Override
            public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
                if (Request.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RequestWrapperJsonSerializer(serializer);
                }
                return serializer;
            }
        });
        ObjectMapper mapper = JsonMapper.builder()
                .enable(SerializationFeature.INDENT_OUTPUT)
                .addModule(wrappersModule)
                .build();

        System.out.println(mapper.writeValueAsString(new Request1(1, "POST")));
        System.out.println(mapper.writeValueAsString(new Request2(2, UUID.randomUUID())));
    }
}

class RequestWrapperJsonSerializer extends JsonSerializer<Request> {

    private final JsonSerializer baseSerializer;

    public RequestWrapperJsonSerializer(JsonSerializer baseSerializer) {
        this.baseSerializer = baseSerializer;
    }

    @Override
    public void serialize(Request value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeFieldName(value.getClass().getSimpleName() + "Wrapper");
        gen.writeStartObject();
        baseSerializer.unwrappingSerializer(NameTransformer.NOP).serialize(value, gen, serializers);
        gen.writeEndObject();
        gen.writeEndObject();
    }
}

abstract class Request {
    private int id;

    //constructor, getters, setters, toString
}

class Request1 extends Request {
    private String body;

    //constructor, getters, setters, toString
}

class Request2 extends Request {

    private UUID uuid;

    //constructor, getters, setters, toString
}

上面的代码显示:

{
  "Request1Wrapper" : {
    "id" : 1,
    "body" : "POST"
  }
}
{
  "Request2Wrapper" : {
    "id" : 2,
    "uuid" : "dd4cccb5-1cf5-4dd4-8bc7-97cb101e5d7d"
  }
}

您可以使用serialize方法代替unwrappingSerializer方法,并删除多余的包装调用.

Instead unwrappingSerializer method you can use serialize method and remove extra wrapping invocations.

这篇关于@JsonSerialize-如何在运行时创建包装器并为对象字段使用默认序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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