问题
I want to be able to read/write Json object from/to disk.
I admit, in Java it would have been taking me about 10 minutes.
Scala is a bit more challenging. I think that the main reason is not enough info on the net.
Anyway, this is what I have done so far:
package com.example
import java.io.{BufferedWriter, FileWriter}
import spray.json._
import spray.json.DefaultJsonProtocol
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
object Test {
object Foo extends DefaultJsonProtocol {
implicit val fooFormat = jsonFormat2(Foo.apply)
}
case class Foo(name: String, x: String) {
//def toJson:JsValue = JsObject( "name" -> JsString(name) )
}
def main(args: Array[String]) {
println("Hello, world!")
implicit val foo = new Foo("xxx", "jj")
println(foo.toJson)
val w = new BufferedWriter(new FileWriter("output.txt"))
w.write(x.toJson) // This doesn't work. I also tried: x.toJson.toString
}
}
回答1:
Aw, that's disappointing. I contributed a diagram to the spray-json readme that I hoped would be helpful to newcomers. But you still have to figure out what to do about the implicits.
Spray-json uses typeclasses to serialize/deserialize objects. You might want to read up on typeclasses, but the important thing to know here is that implicit JsonFormat objects have to be in scope for all of the classes used by the object and the things it references. The DefaultJsonProtocol trait contains implicit JsonFormats for common Scala types, and you must provide your own implicit JsonFormats for your own types. The jsonFormat1,2,... methods provide an easy way to create such JsonFormats for case classes.
There are a number of problems with your program. Here's a simple one that works:
import spray.json._
import java.io.{BufferedWriter, FileWriter}
object Test extends App with DefaultJsonProtocol {
case class Foo(name: String, x: String)
implicit val fooFormat = jsonFormat2(Foo.apply)
val foo = Foo("xxx", "jj")
println(foo.toJson)
val w = new BufferedWriter(new FileWriter("output.txt"))
w.write(foo.toJson.prettyPrint)
w.close
}
来源:https://stackoverflow.com/questions/27206068/how-do-i-write-read-to-from-disk-spray-json-object