Home > OS >  json parsing using circe in scala
json parsing using circe in scala

Time:08-05

I'm trying to make use of circe for json parsing in scala. Can you please help me parse 'pocs' from the data in the case class as well? here is the code:

import io.circe.Decoder
import io.circe.generic.semiauto.deriveDecoder
import io.circe.parser

val json: String =
"""
{
    "segmements": [
        {
            "tableName": "X",
            "segmentName": "XX",
            "pocs": [
                "[email protected]",
                "[email protected]"
            ]
        },
        {
            "tableName": "Y",
            "segmentName": "YY",
            "pocs": [
                "[email protected]",
                "[email protected]"
            ]
        }
    ]
}
"""

final case class TableInfo(tableName: String, segmentName: String)
object TableInfo {
  implicit final val TableInfoDecoder: Decoder[TableInfo] = deriveDecoder
}

val result = for {
  data <- parser.parse(json)
  obj <- data.asObject.toRight(left = new Exception("Data was not an object"))
  segmements <- obj("segmements").toRight(left = new Exception("Json didn't had the 
segments key"))
  r <- segmements.as[List[TableInfo]]
} yield r

println(result)

scastie link: https://scastie.scala-lang.org/BalmungSan/eVEvBulOQwGzg5hIJroAoQ/3

CodePudding user response:

Just add parameter typed as collection of String:

final case class TableInfo(tableName: String, segmentName: String, pocs: Seq[String])

scastie

  • Related