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.
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.
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.
Jackson mapper fill the ArrayList maintaining the order of JSON. If you want a different order you can use the annotation @JsonPropertyOrder.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With