Given this json:
{
"id": "1",
"details": [{
"tax": [{
"amount": 1
},
{
"amount": 2
}]
}]
}
I'm trying to reading it in this way:
lazy val amounts: List[BigDecimal] = parse(json) \\ "amount" \ classOf[JDecimal]
But it's giving me an empty list, while using JDouble
like this:
lazy val amounts: List[Double] = parse(json) \\ "amount" \ classOf[JDouble]
It's giving me the correct list.
How can I directly read a list of BigDecimals
?
Shortly you can solve it by using extract
method with target type
for this conversion, like:
val amounts = parse(json) \ "details" \ "tax" \ "amount"
implicit val formats = DefaultFormats
val decimals = amounts.extract[List[BigDecimal]]
> List(1, 2)
Explanation:
When read amounts
it's element type is JInt
not JDecimal
,
val amounts = parse(json) \ "details" \ "tax" \ "amount"
> JArray(List(JInt(1), JInt(2)))
as you can see it's JInt
type for the amounts
.
and for extracting by class
type:
def \[A <: JValue](clazz: Class[A]): List[A#Values] =
findDirect(jv.children, typePredicate(clazz) _).asInstanceOf[List[A]] map { _.values }
it's predicating
by clazz
, but the amounts
's element type is JInt
, so it's will return an empty list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.