我习惯于使用sacla spray json来序列化和反序列化json数据。但是有一个问题困扰了我很长一段时间:假设json数据是:
{"a":"123"}但有时可能是:
{"a":123} or {"a":123.0}问题是我事先不知道数据类型,它可能是String、Int或Doule。
在使用spray json框架时,需要提前确定数据格式。下面是我的代码:
case class Input(a:Either[String,Numeric[Either[Int,Doule]]])
object SelfJsonProtocol extends DefaultJsonProtocol {
// format the json type into scala type.
implicit val InputFormat = jsonFormat1(Input)
}但是在编译它的时候,这是错误的。有人能帮我吗?
发布于 2017-06-29 05:05:10
实际上,如果稍微简化一下,case类中的任一类型都可以工作。使用EitherDouble,String。这样,Int会自动解析为双精度。
示例:
import spray.json._
case class DoubleTest(a: Either[Double, String])
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val doubleTestFormat = jsonFormat1(DoubleTest)
}
import MyJsonProtocol._
val json = """[{"a":"123"}, {"a":123}, {"a":123.0}]"""
val ast = JsonParser(json)
val DTs = ast.convertTo[List[DoubleTest]]
DTs.map { dt =>
dt.a match {
case Left(d) => { println("double found"); d }
case Right(d) => { println("string found"); d.toDouble }
}
}输出:
json: String = [{"a":"123"}, {"a":123}, {"a":123.0}]
ast: spray.json.JsValue = [{"a":"123"},{"a":123},{"a":123.0}]
DTs: List[DoubleTest] = List(DoubleTest(Right(123)), DoubleTest(Left(123.0)), DoubleTest(Left(123.0)))
string found
double found
double found
res35: List[Double] = List(123.0, 123.0, 123.0)https://stackoverflow.com/questions/44799837
复制相似问题