使用 Spray Json 将 Any 的二维序列转换为 Json
Use Spray Json to convert 2D sequence of Any into 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
如果有任何提示或片段可以帮助我理解这一点,我将不胜感激。
您可以使用编码器,例如:
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"]]
这是此 post 的改编版本:使用 spray 序列化 Map[String, Any] json
注意 null
案例的 NullPointerException 处理。
我正在尝试了解 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
如果有任何提示或片段可以帮助我理解这一点,我将不胜感激。
您可以使用编码器,例如:
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"]]
这是此 post 的改编版本:使用 spray 序列化 Map[String, Any] json
注意 null
案例的 NullPointerException 处理。