Saturday, October 19, 2019

Write / Read / Parse / Pretty Print JSON using Jackson FasterXML


Jackson provide writeValue() and readValue() methods to convert Java objects to / from JSON.


mapper.writeValue – Java Objects to JSON
ObjectMapper mapper = new ObjectMapper();

// Write Java object to JSON file
mapper.writeValue(new File("c:\\test\\staff.json"), new Staff());

// Encode Java object to JSON string, default compact-print
String jsonString = mapper.writeValueAsString(new Staff());
 
// Encode Java object to JSON string with Pretty Print
String jsonPrettyString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Staff());

mapper.readValue – JSON to Java Objects
 ObjectMapper mapper = new ObjectMapper();

 //JSON file to Java object
 Staff obj = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class);

 //JSON URL to Java object
 Staff obj = mapper.readValue(new URL("http://some-domains/api/staff.json"), Staff.class);

 //JSON string to Java Object
 Staff obj = mapper.readValue("{'name' : 'mkyong'}", Staff.class);


Download Jackson

Declares jackson-databind, it will pull in jackson-annotations and jackson-core
pom.xml
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
 </dependency>

Reference:



Previous Post
Next Post

0 komentar: