JacksonDemo.java

Download JacksonDemo.java

 1: //package com.wpollock.JacksonDemo;
 2: 
 3: import java.time.LocalDate;
 4: import java.util.*;
 5: 
 6: import com.fasterxml.jackson.core.JsonProcessingException;
 7: import com.fasterxml.jackson.databind.ObjectMapper;
 8: import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
 9: 
10: /**
11:  * Demo of Jackson JSON object mapping.
12:  *
13:  * Jackson is a fast, powerful (flexible) data processing library.  Here
14:  * we show converting a complex Java object to JSON and back.  To allow
15:  * correct round-trip conversions, you need the generated JSON to include
16:  * the object types (normally omitted from JSON).  To use the new LocalDate
17:  * class requires an add-on module, since class LocalDate doesn't have a
18:  * normal constructor (and thus causes an exception when Jackson tries to
19:  * create one).
20:  *
21:  * (Note Maven requires four dependencies for Jackson in this case:
22:  * jackson-core, jackson-annotations, jackson-databind, and
23:  * jackson-datatype-jsr310, all from groupID "com.fasterxml.jackson.core".)
24:  *
25:  * @author wpollock
26:  *
27:  */
28: public class JacksonDemo {
29: 
30: 	public static void main(String[] args) throws Exception {
31: 
32: 		ObjectMapper mapper = new ObjectMapper();  // Jackson JSON-Object
33: 		mapper.registerModule(new JavaTimeModule());
34: 		mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
35: 
36: 		Map<String, Set<LocalDate>> map = new HashMap<>();
37: 		Set<LocalDate> set = new HashSet<>();
38: 		set.add(LocalDate.now());
39: 		map.put("One", set);
40: 
41: 		set = new HashSet<>();
42: 		set.add(LocalDate.of(2019, 04, 25));
43: 		set.add(LocalDate.of(2018, 12, 31));
44: 		map.put("Two", set);
45: 
46: 		System.out.println("Original map:\n" + map);
47: 
48: 		// Object to JSON String:
49: 		String json = mapper.writeValueAsString(map);
50: 		String jsonPretty =
51: 				mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
52: 
53: 		System.out.println("JSON (Pretty-printing):\n" + jsonPretty);
54: 		System.out.println("JSON:\n" + json);
55: 
56: 		// JSON to object:
57: 		Map<String, Set<LocalDate>> resultMap = new HashMap<>();
58: 		resultMap = mapper.readValue(json, map.getClass());
59: 
60: 		System.out.println("Result map:\n" + resultMap);
61: 		System.out.println("Orginal map equals result: "
62: 				+ map.equals(resultMap));
63: 	}
64: }