实际上,只要稍微简化一点,case类中的任何一种类型都可以工作。使用[Double,String]之一。这样,int会自动解析为double。
例子:
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)