Java CollectionDeserializer-class And Method Code Example
Here is an example of how to use the CollectionDeserializer
class from the Jackson Databind library to deserialize a collection from JSON:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.CollectionDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
public class CustomCollectionDeserializer extends CollectionDeserializer {
public CustomCollectionDeserializer(JavaType collectionType, JsonDeserializer<Object> deserializer) {
super(collectionType, deserializer);
}
@Override
public Collection<Object> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Collection<Object> collection = new ArrayList<>();
while (p.nextToken() != JsonToken.END_ARRAY) {
Object value = deserializer.deserialize(p, ctxt);
collection.add(value);
}
return collection;
}
}
You can then use this custom deserializer by registering it with the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Collection.class, new CustomCollectionDeserializer(mapper.getTypeFactory().constructCollectionType(Collection.class, MyClass.class), mapper.findValueDeserializer(MyClass.class)));
mapper.registerModule(module);
Then you can deserialize your JSON to Collection as follow:
Collection<MyClass> myCollection = mapper.readValue(jsonString, new TypeReference<Collection<MyClass>>(){});
Please note that the above example is just a skeleton code, you may need to handle the exception and add proper validation based on your use case.