nam
nam

Reputation: 3632

how to parse un Array of object with Circe

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) ?

Upvotes: 0

Views: 2279

Answers (2)

Ryan
Ryan

Reputation: 516

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)

Upvotes: 0

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

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)

Upvotes: 3

Related Questions