Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

json parsing using circe in scala

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": [
                "aa@aa.com",
                "bb@bb.com"
            ]
        },
        {
            "tableName": "Y",
            "segmentName": "YY",
            "pocs": [
                "aa@aa.com",
                "bb@bb.com"
            ]
        }
    ]
}
"""

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just add parameter typed as collection of String:

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

scastie

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading