我正在尝试实现一个编写 Doubles 的函数,该函数的值可能为 Infinity(JSON 中不存在)。
以下是我想要实现的一些示例:
Input: Double.PositiveInfinity
Output:
{
"positiveInfinty": true,
"negativeInfinty": false,
"value": null
}
Input: 12.3
Output:
{
"positiveInfinty": false,
"negativeInfinty": false,
"value": 12.3
}
到目前为止,我已经创建了一个增强的 JsPath 类,并添加了名为writeInfinite
:
case class EnhancedJsPath(jsPath: JsPath) {
private def infinityObject(pos: Boolean, neg: Boolean, value: Option[Double]): JsObject = Json.obj(
"positiveInfinity" -> pos,
"negativeInfinity" -> neg,
"value" -> value
)
def writeInfinite: OWrites[Double] = OWrites[Double] { d =>
if (d == Double.PositiveInfinity) { infinityObject(true, false, None) }
else if (d == Double.NegativeInfinity) { infinityObject(false, true, None) }
else { infinityObject(false, false, Some(d)) }
}
}
object EnhancedJsPath {
implicit def jsPathToEnhancedJsPath(jsPath: JsPath): EnhancedJsPath = EnhancedJsPath(jsPath)
}
代码全部编译,这是我正在使用的测试:
case class Dummy(id: String, value: Double)
object Dummy {
implicit val writes: Writes[Dummy] = (
(JsPath \ "id").write[String] and
(JsPath \ "value").writeInfinite
)(unlift(Dummy.unapply))
}
test("EnhancedJsPath.writesInfinite should set positive infinity property") {
val d = Dummy("123", Double.PositiveInfinity, Some(Double.PositiveInfinity))
val result = Json.toJson(d)
val expected = Json.obj(
"id" -> "123",
"value" -> Json.obj(
"positiveInfinity" -> true,
"negativeInfinity" -> false,
"value" -> JsNull
)
)
assert(result == expected)
}
测试失败,因为值为result
:
{
"id": "123",
"positiveInfinity": true,
"negativeInfinity": false,
"value": null
}
代替:
{
"id": "123",
"value": {
"positiveInfinity": true,
"negativeInfinity": false,
"value": null
}
}
我不知道如何修改我writeInfinite
以尊重路径。