//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author John Miller * @version 1.0 * @date Mon Jan 26 14:56:24 EST 2015 * @see LICENSE (MIT style license file). */ import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.System.out; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `ReadWrite` class provides methods for reading a Json stream into a Java Bean * and writing a Java Bean into a Json stream. * @see http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial */ public class ReadWriteJson { private static ObjectMapper objectMapper = new ObjectMapper (); // create ObjectMapper instance //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Read a file containing Json data into a Java Bean. * @param fname the name of Json file */ public static Employee read (String fname) throws IOException { byte [] jsonData = Files.readAllBytes (Paths.get (fname)); return objectMapper.readValue (jsonData, Employee.class); // convert Json string to object } // read //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Write a Java Bean into a stream (in this case a string). * @param emp the Employee Java Bean to write */ public static StringWriter write (Employee emp) throws IOException { // configure Object mapper for pretty print objectMapper.configure (SerializationFeature.INDENT_OUTPUT, true); StringWriter stringEmp = new StringWriter (); // create string stream objectMapper.writeValue (stringEmp, emp); // write into string stream return stringEmp; } // write //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Run the program via the main method. * @param args the command-line arguments */ public static void main (String [] args) throws IOException { out.println ("Read a Json stream/file into a Java Bean"); Employee emp = read ("employee.txt"); out.println ("Employee Object:\n" + emp); out.println ("Write a Java Bean into a Json stream"); StringWriter stringEmp = write (emp); out.println ("Employee Json:\n" + stringEmp); } // main } // ReadJson class