Object Mapping - Jackson
Two popular libraries to map JSON data with Java objects.
Jackson
Dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
Anotation
@JsonIgnoreProperties(ignoreUnknown = true) // ignore properties that not defined in the class
@JsonInclude(JsonInclude.Include.NON_NULL) // null value shoudn't be read in
@JsonProperty("titile") //match title with the class variable
public String getTitle() {
return title;
}
Mapper Usage
- Mapping from JSON file directly, i.e., JSON is flat data that includes the object data.
ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(entity.getContent(), Item.class); // to single object
Item[] times = mapper.readValue(entity.getContent(), Item[].class); // to object array
- Mapping from nested array of object using JsonNode.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(entity.getContent()); // read content to JsonNode
JsonNode jobs = jsonNode.get("jobs"); // get a value from the key jobs
List<Item> items = new ArrayList(Arrays.asList(mapper.readValue(jobs.toString(), Item[].class))); // mapper them to an array of Items.
Written on May 13, 2021