0

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?

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57

1 Answers1

1

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.

chengpohi
  • 14,064
  • 1
  • 24
  • 42