I have the following code that does not compile and returns this error:
error: could not find implicit value for parameter d: io.circe.Decoder[List[TableInfo]]
r <- segmements.as[List[TableInfo]]
[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:
Try this way
import io.circe.Decoder
import io.circe.generic.semiauto.deriveDecoder
import io.circe.parser
import io.circe._
val json: String =
"""
{
"segments": [
{
"tableName": "X",
"segmentName": "XX",
"pocs": [
"[email protected]",
"[email protected]"
]
},
{
"tableName": "Y",
"segmentName": "YY",
"pocs": [
"[email protected]",
"[email protected]"
]
}
]
}
"""
final case class Tables(segments: List[TableInfo])
object Tables {
implicit val decoder: Decoder[Tables] = (cursor: HCursor) =>
for {
segments <- cursor.downField("segments").as[List[TableInfo]]
} yield Tables(segments)
}
final case class TableInfo(tableName: String, segmentName: String)
object TableInfo {
implicit final val TableInfoDecoder: Decoder[TableInfo] = deriveDecoder
}
val result = io.circe.parser.decode[Tables](json)
println(result)
CodePudding user response:
I added import import TableInfo._ to the code before val result as @ Luis Miguel Mejía Suárez recommended and the code worked as intended.