Java AtomicReferenceDeserializer-class And Method Code Example
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceDeserializer<T> extends StdDeserializer<AtomicReference<T>> {
private Class<T> clazz;
public AtomicReferenceDeserializer(Class<T> clazz) {
super(AtomicReference.class);
this.clazz = clazz;
}
@Override
public AtomicReference<T> deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode node = parser.getCodec().readTree(parser);
T value = context.readValue(node.traverse(), clazz);
return new AtomicReference<>(value);
}
}
This is an example of a custom deserializer for the AtomicReference class in Jackson. It extends StdDeserializer and overrides the deserialize method to handle converting a JSON value to an AtomicReference instance.
It takes the Class of the type of reference this deserializer will handle, so that it can use the context.readValue to deserialize the value from json.
You will need to use this deserializer along with ObjectMapper.registerModule() method to register this deserializer to be used by the ObjectMapper.