2

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

Vish0111
  • 43
  • 6

1 Answers1

1

Just add parameter typed as collection of String:

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

scastie

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thank you for the answer. I'm a little new to Scala, Can you please tell me a little more about the last line of code Right(List(TableInfo( I couldn't understand it clearly. Thank you. – Vish0111 Aug 04 '22 at 17:35
  • @Vish0111 it's scastie feature - basically it outputs the value of `result` (like `println` but without it) with type info. You can just remove `result` and it will [disappear also](https://scastie.scala-lang.org/Ia2vVtpOT822P6Dk4UQAZg) You can see the same near `println` - `(): Unit` which basically return of `println`. – Guru Stron Aug 04 '22 at 17:39