Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson read json in generic List

I'm using Jackson in order to read json messages. One of the values that I' trying to parse is a List and another value contains the type of the data in the list. This is the structure i 've created in java.

public class Message<T> {    private Timestamp time;    private RestAction action;    private String type;    private List<T> data; } 

Through Class.forName(); I can get the class which represents the data in the list. The question is how can I read the List.

like image 750
Lalao Avatar asked Jul 31 '13 19:07

Lalao


People also ask

How does Jackson parse JSON?

databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

Does Jackson preserve array order?

Jackson mapper fill the ArrayList maintaining the order of JSON. If you want a different order you can use the annotation @JsonPropertyOrder.

Does Jackson support JsonPath?

The Jayway JsonPath library has support for reading values using a JSON path. If you would like to specifically use GSON or Jackson to do the deserialization (the default is to use json-smart), you can also configure this: Configuration.


1 Answers

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>>() {}

like image 82
splatch Avatar answered Sep 28 '22 16:09

splatch