使用 json4s return 空列表反序列化 scala 中的 BigDecimal
Deserialize BigDecimal in scala with json4s return empty list
鉴于此 json:
{
"id": "1",
"details": [{
"tax": [{
"amount": 1
},
{
"amount": 2
}]
}]
}
我正在尝试以这种方式阅读它:
lazy val amounts: List[BigDecimal] = parse(json) \ "amount" \ classOf[JDecimal]
但它给了我一个空列表,同时使用 JDouble
像这样:
lazy val amounts: List[Double] = parse(json) \ "amount" \ classOf[JDouble]
它给了我正确的列表。
如何直接读取 BigDecimals
的列表?
很快你可以通过使用 extract
方法和目标 type
来解决这个问题,比如:
val amounts = parse(json) \ "details" \ "tax" \ "amount"
implicit val formats = DefaultFormats
val decimals = amounts.extract[List[BigDecimal]]
> List(1, 2)
解释:
当读取 amounts
时,它的元素类型是 JInt
而不是 JDecimal
、
val amounts = parse(json) \ "details" \ "tax" \ "amount"
> JArray(List(JInt(1), JInt(2)))
如您所见,它是 amounts
的 JInt
类型。
并通过 class
类型提取:
def \[A <: JValue](clazz: Class[A]): List[A#Values] =
findDirect(jv.children, typePredicate(clazz) _).asInstanceOf[List[A]] map { _.values }
它是 clazz
的 predicating
,但是 amounts
的元素类型是 JInt
,所以它将 return 一个空列表。
鉴于此 json:
{
"id": "1",
"details": [{
"tax": [{
"amount": 1
},
{
"amount": 2
}]
}]
}
我正在尝试以这种方式阅读它:
lazy val amounts: List[BigDecimal] = parse(json) \ "amount" \ classOf[JDecimal]
但它给了我一个空列表,同时使用 JDouble
像这样:
lazy val amounts: List[Double] = parse(json) \ "amount" \ classOf[JDouble]
它给了我正确的列表。
如何直接读取 BigDecimals
的列表?
很快你可以通过使用 extract
方法和目标 type
来解决这个问题,比如:
val amounts = parse(json) \ "details" \ "tax" \ "amount"
implicit val formats = DefaultFormats
val decimals = amounts.extract[List[BigDecimal]]
> List(1, 2)
解释:
当读取 amounts
时,它的元素类型是 JInt
而不是 JDecimal
、
val amounts = parse(json) \ "details" \ "tax" \ "amount"
> JArray(List(JInt(1), JInt(2)))
如您所见,它是 amounts
的 JInt
类型。
并通过 class
类型提取:
def \[A <: JValue](clazz: Class[A]): List[A#Values] =
findDirect(jv.children, typePredicate(clazz) _).asInstanceOf[List[A]] map { _.values }
它是 clazz
的 predicating
,但是 amounts
的元素类型是 JInt
,所以它将 return 一个空列表。