0

I am serializing multiple lists within the same object and would like to call clear() on all list after the object has been serialized.

The current approach is to call clear() manually on each list after serialization but I am hoping there is a more robust approach, such as using a custom JsonSerializer or perhaps an AtomicReference.

I have little experience with JsonSerializer and am hoping someone could provide an example that accomplishes this.

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;
 }
 }
}
asked Sep 27, 2018 at 18:43

1 Answer 1

1

Something like the following:

public class ResetSerializer extends JsonSerializer<Collection> {
 @Override
 public void serialize(Collection t, JsonGenerator jg, SerializerProvider sp) throws IOException {
 if (t != null) {
 jg.writeStartArray();
 for (Object o: t) {
 jg.writeObject(o);
 }
 jg.writeEndArray();
 t.clear();
 }
 }
}

Notice that this method has void return type, i.e. it is not expected to return something. It applies the side-effects that are written in the serialized version of the object.

answered Sep 27, 2018 at 18:53
Sign up to request clarification or add additional context in comments.

4 Comments

Ah yes, thank you. As for the writeObjectField(String, Object), how I would inherit the name of the field that is being serialized? There are many list that will use this serializer and I imagine specifying a field name could pose problems. It would also limit the serializer to a very specific field. Would jg.getOutputContext().getCurrentName() suffice?
Specify name on each field as @JsonProperty("nameList").
My question was directed to the line jg.writeObjectField("jsonList", t). Unless @JsonProperty overrides the value specified on writeObjectField().
Right..check the current modification.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.