Jackson read json in generic List Jackson read json in generic List json json

Jackson read json in generic List


Something which is much shorter:

mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});

Where EntryType is a reference to type you would like to hold within collection. It might be any Java class.For example to read JSON representation such as ["a", "b", "c"] second argument to mapper should be new TypeReference<List<String>>() {}


If you need to map the incoming json to your List you can do like this

String jsonString = ...; //Your incoming json stringObjectMapper mapper = new ObjectMapper();Class<?> clz = Class.forName(yourTypeString);JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clz);List <T> result = mapper.readValue(jsonString, type);

Edit

Something like this, completly untested and never done

public Message<T> deserialize(JsonParser jsonParser, DeserializationContext arg1)    throws IOException, JsonProcessingException {    ObjectMapper mapper = new ObjectMapper();    ObjectCodec oc = jsonParser.getCodec();    JsonNode node = oc.readTree(jsonParser);    JsonNode timeStamp = node.get("time");    Timestamp time = mapper.readValue(timeStamp, Timestamp.class);    JsonNode restAction = node.get("action");    RestAction action = mapper.readValue(restAction, RestAction.class);    String type = node.get("type").getTextValue();    Class<?> clz = Class.forName(type);    JsonNode list = node.get("data");    JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class,   clz);    List <T> data = mapper.readValue(list, listType);    Message<T> message = new Message<T>;    message.setTime(time);    message.setAction(action);    message.setType(type);    message.setData(data);    return message;}


You need to annotate your class with @JsonDeserialize(using = MessageDeserializer.class) and implement custom deserializer:

public class MessageDeserializer extends JsonDeserializer<Message> {  @Override  public Message deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)    throws IOException, JsonProcessingException {    // YOU DESERIALIZER CODE HERE  }}

@see examples here: How Do I Write a Jackson JSON Serializer & Deserializer?