简体   繁体   English

如何使用JACKSON进行自定义序列化/反序列化?

[英]How to do custom serialization/deserialization using JACKSON?

I am trying to convert the following gson serialization to JACKSON serialization. 我试图将以下gson序列化转换为JACKSON序列化。 Please let me know what i need to change to make it work for JACKSON 请让我知道我需要更改什么才能让它适用于JACKSON

public class AbstractElementAdapter 
    implements JsonSerializer<AbstractElement>, JsonDeserializer<AbstractElement>
{
    @Override
    public JsonElement serialize(AbstractElement src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        JsonObject properties = context.serialize(src, src.getClass()).getAsJsonObject();

        if (src instanceof TruncatedElement) {
            result.add("type", new JsonPrimitive(((TruncatedElement) src).getClassName()));
            properties.remove("className");
        } else {
            result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
        }

        result.add("properties", properties);

        return result;
    }

    @Override
    public AbstractElement deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get("type").getAsString();
        JsonElement element = jsonObject.get("properties");

        try {
            return context.deserialize(element, Class.forName("com.zreflect.emyed.whiteboard.model.element." + type));
        } catch (ClassNotFoundException cnfe) {
            throw new JsonParseException("Unknown element type: " + type, cnfe);
        }
    }
}

You can create a custom serializer, something like this: 您可以创建自定义序列化程序,如下所示:

  public class ItemSerializer extends JsonSerializer<AbstractElement> {
        @Override
        public void serialize(AbstractElement src, JsonGenerator jgen, SerializerProvider provider)
                throws IOException, JsonProcessingException {
            jgen.writeStartObject();

            if (src instanceof TruncatedElement) {
                jgen.writeStringField("type",((TruncatedElement) src).getClassName());
                jgen.writeObjectFieldStart("properties");
                //use  jgen.writeStringField();  
                //jgen.writeNumberField(); 
                //etc to every one of the values, 
                //but skipping className
                 jgen.writeEndObject();


            } else {
                jgen.writeStringField("type", src.getClass().getSimpleName() );
                //write everythin
                jgen.writeObjectField("properties", src);
            }

            jgen.writeEndObject();
        }
    }

And register it with the ObjectMapper and then do the serialization: 并使用ObjectMapper注册它,然后进行序列化:

ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(yourObject.class, new ItemSerializer());
mapper.registerModule(module);

String serialized = mapper.writeValueAsString(yourObject);

To the trick of skipping className , you could also want to use a custom field filter, you have a great example here: http://www.baeldung.com/jackson-ignore-properties-on-serialization 对于跳过className的技巧,您可能还想使用自定义字段过滤器,这里有一个很好的例子: http//www.baeldung.com/jackson-ignore-properties-on-serialization

Jackson allows you to specify serializers through annotations. Jackson允许您通过注释指定序列化程序。 For example, see the trivial example below: 例如,请参阅下面的简单示例:

@JsonSerialize(using FooToStringSerializer)
public class Foo implements Serializable {

    private String bar;

    public Foo(String bar) {
        this.bar = bar;
}

Then, if all I wanted to see when the object was serialized was bar , I would create the serializer like so: 然后,如果所有我想要查看对象序列化的时间是bar ,我会像这样创建序列化器:

public class FooToStringSerializer extends JsonSerializer<Foo> {

    @Override
    public void serialize(final Foo value, final JsonGenerator jgen,
        final SerializerProvider provider) throws IOException
    {
        jgen.writeObject(value.getBar());
    }

For deserialization, you can create a deserializer and register it with the ObjectMapper that will be doing the deserialization. 对于反序列化,您可以创建反序列化器并将其与将要执行反序列化的ObjectMapper一起注册。

To register a deserializer with an object mapper, do the below: 要使用对象映射器注册反序列化器,请执行以下操作:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new FooDeserializer());
mapper.registerModule(module);

For a really easy to follow example of custom deserialization, see this link: http://www.baeldung.com/jackson-deserialization 有关自定义反序列化的简单示例,请参阅以下链接: http//www.baeldung.com/jackson-deserialization

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

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