如何写入磁盘Spray json对象或从磁盘Spray json对象读取数据? [英] How do I write/read to/from disk Spray json object?

查看:105
本文介绍了如何写入磁盘Spray json对象或从磁盘Spray json对象读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从磁盘读取/写入磁盘中的Json对象.

I want to be able to read/write Json object from/to disk.

我承认,在Java中,这大约要花我10分钟.

I admit, in Java it would have been taking me about 10 minutes.

Scala更具挑战性.我认为主要原因是网络上的信息不足.

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
  }
}

推荐答案

噢,真令人失望.我为 spray-json自述文件提供了图表,希望对新手有所帮助.但是您仍然必须弄清楚如何处理隐式.

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使用类型类对对象进行序列化/反序列化.您可能想要阅读类型类,但是要知道的重要一点是,隐式JsonFormat对象必须在该对象使用的所有类及其引用的对象的范围内. DefaultJsonProtocol特征包含常见Scala类型的隐式JsonFormats,并且您必须为自己的类型提供自己的隐式JsonFormats. jsonFormat1,2,...方法提供了一种为案例类创建此类JsonFormats的简便方法.

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
}

这篇关于如何写入磁盘Spray json对象或从磁盘Spray json对象读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆