0

I have a json

{ "field" : [ { "value" : 1.0 }, { "value" : 2.0 } ] }

How do I get a List[String] that are of values List(1.0, 2.0) ?

nam
  • 3,542
  • 9
  • 46
  • 68

2 Answers2

3

Personally I would do it like:

import io.circe.generic.auto._
import io.circe.parser.decode

case class ValueWrapper(value: Double)
case class Result(field: Seq[ValueWrapper])

decode[Result](jsonString).map(_.field.map(_.toString)).getOrElse(Seq.empty)

Actually, you could do that without Decoder derivation. Basically it means that you do not use most often used part of Circe, and instead rely on Circe optics. I guess it would be sth like (I haven't tested it!):

import io.circe.optics.JsonPath._
root.field.value.double.getAll(jsonString).map(_.toString)
Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
0

Circe optics is the most concise way to do that.

import io.circe.optics.JsonPath._
import io.circe.parser._

val json = parse(jsonStr).right.get // TODO: handle parse errors

root.field.each.value.double.getAll(json) // == List(1.0, 2.0)
Ryan
  • 496
  • 6
  • 13