Followings are quick getting started examples of using Jackson API for JSON processing. The examples shows the basic data-binding capabilities of Jackson's ObjectMapper class.
Maven dependency
pom.xml<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
Simple Java Object Conversion To Json: ObjectMapper om = new ObjectMapper();
Map<String, Integer> map = Map.of("one", 1, "two", 2);
String s = om.writeValueAsString(map);
System.out.println(s);
{"one":1,"two":2}
To Java Object: ObjectMapper om = new ObjectMapper();
String jsonString = "{\"bananas\":2,\"apple\":5}";
Map<String, Integer> map = om.readValue(jsonString, Map.class);
System.out.println(map);
System.out.println(map.getClass());
{bananas=2, apple=5} class java.util.LinkedHashMap
POJO Conversion public class MyObject {
private int intVal;
private String StringVal;
private List<String> list;
.............
} To Json: MyObject pojo = new MyObject();
pojo.setIntVal(3);
pojo.setStringVal("test string");
pojo.setList(List.of("item1", "item2"));
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(pojo);
System.out.println(s);
{"intVal":3,"list":["item1","item2"],"stringVal":"test string"}
To Pojo: String s = "{\"list\":[\"item3\",\"item4\"],\"stringVal\":\"test string2\",\"intVal\":5}";
ObjectMapper om = new ObjectMapper();
MyObject obj = om.readValue(s, MyObject.class);
System.out.println(obj);
MyObject{intVal=3, StringVal='test string', list=[item1, item2]}
Conversion Involving Java Generics As seen in the first example above, Jackson can handle generics for simple types. Let's try generics of a POJO: To Json: MyObject pojo = new MyObject();
pojo.setIntVal(3);
pojo.setStringVal("test string");
pojo.setList(List.of("item1", "item2"));
List<MyObject> list = List.of(pojo);
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(list);
System.out.println(s);
[{"intVal":3,"list":["item1","item2"],"stringVal":"test string"}]
To Pojo: String s = "[{\"intVal\":3,\"list\":[\"item1\",\"item2\"],\"stringVal\":\"test string\"}]";
ObjectMapper om = new ObjectMapper();
List<MyObject> list = om.readValue(s, List.class);
System.out.println(list.get(0));
System.out.println(list.get(0).getClass());
{intVal=3, list=[item1, item2], stringVal=test string} java.lang.ClassCastException: java.base/java.util.LinkedHashMap cannot be cast to com.logicbig.example.MyObject at com.logicbig.example.PojoTypeReference.toPojo(PojoTypeReference.java:34)
As seen in above output, Jackson cannot infer the actual type (because of Java type erasure problem) and returns 'list of Map' (LinkedHashMap) instead of 'list of MyObject'. To fix that, we need to indicate actual type by providing Jackson's TypeReference anonymous instance: String s = "[{\"intVal\":3,\"list\":[\"item1\",\"item2\"],\"stringVal\":\"test string\"}]";
ObjectMapper om = new ObjectMapper();
List<MyObject> list = om.readValue(s, new TypeReference<List<MyObject>>() { });
System.out.println(list.get(0));
System.out.println(list.get(0).getClass());
MyObject{intVal=3, StringVal='test string', list=[item1, item2]} class com.logicbig.example.MyObject
Reading Writing files MyObject myObject = new MyObject();
myObject.setIntVal(3);
myObject.setStringVal("test string");
myObject.setList(List.of("item1", "item2"));
//create temp file
File tempFile = File.createTempFile("jackson-", ".txt");
System.out.println("-- saving to file --");
System.out.println(tempFile);
//write myObject as JSON to file
ObjectMapper om = new ObjectMapper();
om.writeValue(tempFile, myObject);
//reading
System.out.println("-- reading as text from file --");
String s = new String(Files.readAllBytes(tempFile.toPath()));
System.out.println(s);
System.out.println("-- reading as Object from file --");
MyObject myObject2 = om.readValue(tempFile, MyObject.class);
System.out.println(myObject2);
-- saving to file -- C:\Users\Joe\AppData\Local\Temp\jackson-3890415751750072504.txt -- reading as text from file -- {"intVal":3,"list":["item1","item2"],"stringVal":"test string"} -- reading as Object from file -- MyObject{intVal=3, StringVal='test string', list=[item1, item2]}
Reading from URL URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
ObjectMapper om = new ObjectMapper();
Object o = om.readValue(url, Object.class);
System.out.println(o);
System.out.println("Read as: "+o.getClass().getName());
{userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto} Read as: java.util.LinkedHashMap
Example ProjectDependencies and Technologies Used: - jackson-databind 2.9.2: General data-binding functionality for Jackson: works on core streaming API.
- JDK 9
- Maven 3.3.9
|
|