//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author John Miller * @version 1.0 * @date Mon Jan 26 14:56:24 EST 2015 * @see LICENSE (MIT style license file). */ import java.io.{IOException, StringWriter} import java.nio.file.Files import java.nio.file.Paths 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 `ReadWrite2` class provides methods for reading a Json stream into a Scala Bean * and writing a Scala Bean into a Json stream. * @see http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial */ object ReadWriteJson2 { private val objectMapper = new ObjectMapper () // create ObjectMapper instance //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Read a file containing Json data into a Scala Bean. * @param fname the name of Json file */ @throws (classOf [IOException]) def read (fname: String): Employee = { val jsonData = Files.readAllBytes (Paths.get (fname)) objectMapper.readValue (jsonData, classOf [Employee]) // convert Json string to object } // read //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Write a Scala Bean into a stream (in this case a string). * @param emp the Employee Scala Bean to write */ @throws (classOf [IOException]) def write (emp: Employee): StringWriter = { // configure Object mapper for pretty print objectMapper.configure (SerializationFeature.INDENT_OUTPUT, true) val stringEmp = new StringWriter () // create string stream objectMapper.writeValue (stringEmp, emp) // write into string stream stringEmp } // write //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Run the program via the main method. * @param args the command-line arguments */ @throws (classOf [IOException]) def main (args: Array [String]) { println ("Read a Json stream/file into a Scala Bean") val emp = read ("employee.txt") println ("Employee Object:\n" + emp) println ("Write a Scala Bean into a Json stream") val stringEmp = write (emp) println ("Employee Json:\n" + stringEmp) } // main } // ReadJson2 object