Warm tip: This article is reproduced from stackoverflow.com, please click
arrays json scala circe

Circe: Json object to Custom Object

发布于 2020-04-03 23:43:36

I've go this json node

...
"businessKeys": [
    "product://color?product_code",
    "product://?code"
  ]
...

after a sequence of computation I have a Json istance but I'm not able to understand how I can transform that object into a List of my object. So Json (istance) to List[MyClass].

MyClass(root: ParameterType, children: List[ParameterType] = List.empty)
ParameterType(parameter: String)

I have a method that transform a String into a MyClass istance, so I need to decode Json into List[String] and then call my function or there is a direct method? Thanks

Questioner
Marco Paggioro
Viewed
90
Ivan Kurchenko 2020-01-31 20:42

You need implement our own io.circe.Decoder, in your case it can be converted from decoder for string.

Please, find some example code below:

import io.circe._
import io.circe.generic.auto._

object CirceExample {
  class ParameterType(parameter: String) {
    override def toString: String = parameter
  }

  class MyClass(root: ParameterType, children: List[ParameterType] = List.empty) {
    override def toString: String = s"MyClass($root, $children)"
  }

  object MyClass {
    /**
     * Parsing logic from string goes here, for sake of example, it just returns empty result
     */
    def parse(product: String): Either[String, MyClass] = {
      Right(new MyClass(new ParameterType("example")))
    }

    // This is what need - just declare own decoder, so the rest of circe infrastructure can use it to parse json to your own class.
    implicit val decoder: Decoder[MyClass] = Decoder[String].emap(parse)
  }

  case class BusinessKeys(businessKeys: List[MyClass])

  def main(args: Array[String]): Unit = {
    val json = "{ \"businessKeys\": [\n    \"product://color?product_code\",\n    \"product://?code\"\n  ] }"
    println(parser.parse(json).map(_.as[BusinessKeys]))
  }
}

Which in my case produced next output:

Right(Right(BusinessKeys(List(MyClass(example, List()), MyClass(example, List())))))

Hope this will help you!