猿问

Jackson 序列化后功能

我在同一个对象中序列化多个列表,并希望clear()在对象序列化后调用所有列表。


当前的方法是在序列化后在每个列表上手动调用 clear() 但我希望有更强大的方法,例如使用自定义JsonSerializer或AtomicReference.


我几乎没有经验,JsonSerializer希望有人能提供一个例子来实现这一点。


public class ResetSerializer extends JsonSerializer<Collection> {


    @Override

    public void serialize(Collection t, JsonGenerator jg, SerializerProvider sp) throws IOException {

        if (t != null) {

            String jsonList = ???; // how do I generate the JSON output of this list with a custom serializer?

            t.clear();

            return jsonList;

       }

    }


}


潇湘沐
浏览 158回答 1
1回答

森栏

类似于以下内容:public class ResetSerializer extends JsonSerializer<Collection> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void serialize(Collection t, JsonGenerator jg, SerializerProvider sp) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; if (t != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jg.writeStartArray();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (Object o: t) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;jg.writeObject(o);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jg.writeEndArray();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t.clear();&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}请注意,此方法具有void返回类型,即不期望返回某些内容。它应用在对象的序列化版本中写入的副作用。
随时随地看视频慕课网APP

相关分类

Java
我要回答