/home/wpollock1/public_html/AJava/JacksonDemo.java
//package com.wpollock.JacksonDemo;
import java.time.LocalDate;
import java.util.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
/**
* Demo of Jackson JSON object mapping.
*
* Jackson is a fast, powerful (flexible) data processing library. Here
* we show converting a complex Java object to JSON and back. To allow
* correct round-trip conversions, you need the generated JSON to include
* the object types (normally omitted from JSON). To use the new LocalDate
* class requires an add-on module, since class LocalDate doesn't have a
* normal constructor (and thus causes an exception when Jackson tries to
* create one).
*
* (Note Maven requires four dependencies for Jackson in this case:
* jackson-core, jackson-annotations, jackson-databind, and
* jackson-datatype-jsr310, all from groupID "com.fasterxml.jackson.core".)
*
* @author wpollock
*
*/
public class JacksonDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper(); // Jackson JSON-Object
mapper.registerModule(new JavaTimeModule());
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
Map<String, Set<LocalDate>> map = new HashMap<>();
Set<LocalDate> set = new HashSet<>();
set.add(LocalDate.now());
map.put("One", set);
set = new HashSet<>();
set.add(LocalDate.of(2019, 04, 25));
set.add(LocalDate.of(2018, 12, 31));
map.put("Two", set);
System.out.println("Original map:\n" + map);
// Object to JSON String:
String json = mapper.writeValueAsString(map);
String jsonPretty =
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println("JSON (Pretty-printing):\n" + jsonPretty);
System.out.println("JSON:\n" + json);
// JSON to object:
Map<String, Set<LocalDate>> resultMap = new HashMap<>();
resultMap = mapper.readValue(json, map.getClass());
System.out.println("Result map:\n" + resultMap);
System.out.println("Orginal map equals result: "
+ map.equals(resultMap));
}
}