使用Spray Json将Any的2D序列转换为Json

时间:2018-03-16 05:26:51

标签: json scala seq spray-json

我正在努力了解Spray Json和Scala的新手。我有Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C'))所以Seq[Seq[Any]]。我不知道该怎么做,我在网上找不到任何例子。

case class SeqFormat(Seq[Seq[Any]]) => {
    // something that would convert to Seq[Seq[String]] 
    //which will would return a Json like this
    //[["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
}

我试过

val someSeq = [["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
val myObj = someSeq.toJson
// This gives me an error saying Any is not valid

我很感激任何提示或片段来帮助我理解这一点。

1 个答案:

答案 0 :(得分:1)

您可以使用编码器,例如:

import spray.json._
import DefaultJsonProtocol._

implicit object AnyJsonFormat extends JsonFormat[Any] {

  def write(x: Any) =
    try {
      x match {
        case n: Int    => JsNumber(n)
        case s: String => JsString(s)
        case c: Char   => JsString(c.toString)
        case _         => JsString("null")
      }
    } catch {
      case _: NullPointerException => JsString("null")
    }

  def read(value: JsValue) = ???
}

您可以使用以下内容:

val input = Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C'))
println(input.toJson)

为了得到:

[["abc",123,"null","null"],["def",45,"1234","C"]]

这是此帖子的改编版本:Serialize Map[String, Any] with spray json

注意null案例的NullPointerException处理。