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

use*_*858 6 java jackson gson

我试图将以下gson序列化转换为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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*een 1

Jackson 允许您通过注释指定序列化器。例如,请参阅下面的简单示例:

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

    private String bar;

    public Foo(String bar) {
        this.bar = bar;
}
Run Code Online (Sandbox Code Playgroud)

然后,如果我想在对象序列化时看到的只是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());
    }
Run Code Online (Sandbox Code Playgroud)

对于反序列化,您可以创建一个反序列化器并将其注册到ObjectMapper将执行反序列化的程序。

要将反序列化器注册到对象映射器,请执行以下操作:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new FooDeserializer());
mapper.registerModule(module);
Run Code Online (Sandbox Code Playgroud)

有关自定义反序列化的真正易于理解的示例,请参阅此链接: http: //www.baeldung.com/jackson-deserialization