Jackson-在要序列化的POJO中更改POJO的序列化程序

ddarikpa  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(69)

我有一个Jackson可序列化对象,它包含了下面几层的其他对象。在某些情况下(可以用@JsonSerialize注解),我想更改该内部对象的序列化。我似乎不知道如何做到这一点。
在下面的示例中,整个Foo对象Request1通过默认序列化进行序列化,但在Request2中,Foo的所有示例都使用自定义序列化程序进行序列化。
请求1 JSON:

{
    id: "8c88e31c-f6da-4ce5-8c75-3cacd5cb6694",
    pojo: {
        foo: {
            value1: "abc",
            value2: "def"
        },
        bar: {
            other: {
                value1: "uvw",
                value2: "xyz"
            }
        }
    }
}

请求2 JSON:

{
    id: "8c88e31c-f6da-4ce5-8c75-3cacd5cb6694",
    pojo: {
        foo: [
            "abc",
            "def"
        ],
        bar: {
            other: [
                "uvw",
                "xyz"
            ]
        }
    }
}

Request1.java:

public class Request1 {
    private UUID id;
    private MyPojo pojo;
}


Request2.java:

public class Request2 {
    private UUID id;

    @JsonSerialize(using = MyPojoSerializer.class)
    private MyPojo pojo;
}

MyPojo.java:

public class MyPojo {
    private Foo foo;
    private Bar bar;

    public static class Bar {
        private Foo other;
    }
}

Foo.java:

public class Foo {
    private String value1;
    private String value2;

用于MyPojo的串行器:

public class MyPojoSerializer extends JsonSerializer<MyPojo> {

    @Override
    public void serialize(final MyPojo value, final JsonGenerator gen,
            final SerializerProvider serializers) throws IOException {
       
        // how to set custom serializer for Foo before serializing the MyPojo object???

        gen.writeObject(value);
    }

    private static class FooSerializer extends JsonSerializer<Foo> {
        @Override
        public void serialize(final Foo value, final JsonGenerator gen,
                final SerializerProvider serializers) throws IOException {
            gen.writeStartArray();
            gen.writeString(value.getValue1());
            gen.writeString(value.getValue2());
            gen.writeEndArray();
        }
    }
}
wtzytmuj

wtzytmuj1#

我不确定是否有一种方法可以在序列化过程中实际注册自定义序列化程序,但是您可以使用以下代码轻松地完成您想要的任务:

public class MyPojoSerializer extends JsonSerializer<MyPojo> {

    @Override
    public void serialize(final MyPojo value, final JsonGenerator gen,
            final SerializerProvider serializers) throws IOException {     
        gen.writeStartObject();
        provider.defaultSerializeField("bar", value.getBar(), gen);
        gen.writeFieldName("foo");
        serializeFoo(value.getFoo(), gen);
        gen.writeEndObject();
    }

    private void serializeFoo(final Foo value, final JsonGenerator gen) throws IOException {
        gen.writeStartArray();
        gen.writeString(value.getValue1());
        gen.writeString(value.getValue2());
        gen.writeEndArray();
    }
}

它并不理想,因为您需要手动序列化每个字段(尽管provider使每个字段成为一行程序),但如果您陷入困境,它至少可以为您提供一条前进的道路。

相关问题