Json 无法解码Circe中的集合
我正在尝试解码这段Json:Json 无法解码Circe中的集合,json,scala,circe,Json,Scala,Circe,我正在尝试解码这段Json: { "id" : "e07cff6a-bbf7-4bc9-b2ec-ff2ea8e46288", "paper" : { "title" : "Example Title", "authors" : [ "1bf5e911-8878-4e06-ba8e-8159aadb052c" ] } } 然而,当它到达集合部分时,它失败了。错误消息没有帮助 DecodingFailure([A]Set[A], List())
{
"id" : "e07cff6a-bbf7-4bc9-b2ec-ff2ea8e46288",
"paper" : {
"title" : "Example Title",
"authors" : [
"1bf5e911-8878-4e06-ba8e-8159aadb052c"
]
}
}
然而,当它到达集合部分时,它失败了。错误消息没有帮助
DecodingFailure([A]Set[A], List())
这是我的文件编码员:
implicit val paperIdDecoder: Decoder[PaperId] = Decoder.decodeString.emap[PaperId] { str ⇒
Either.catchNonFatal(PaperId(str)).leftMap(_.getMessage)
}
implicit val paperAuthorDecoder: Decoder[PaperAuthor] = Decoder.decodeString.emap[PaperAuthor] { str ⇒
Either.catchNonFatal(PaperAuthor(str)).leftMap(_.getMessage)
}
implicit val paperDecoder: Decoder[Paper] = {
for {
title <- Decoder.decodeString
authors <- Decoder.decodeSet[PaperAuthor]
} yield Paper(title, authors)
}
implicit val paperViewDecoder: Decoder[PublishedPaperView] = for {
id <- Decoder[PaperId]
paper <- Decoder[Paper]
} yield PublishedPaperView(id, paper)
虽然错误描述远未明确,但您的问题与解码器的一元API的错误使用有关:请记住,理解的a是map/flatMap的语法糖 从
io.circe.Decoder
/**
* Monadically bind a function over this [[Decoder]].
*/
final def flatMap[B](f: A => Decoder[B]): Decoder[B] = new Decoder[B] {
final def apply(c: HCursor): Decoder.Result[B] = self(c).flatMap(a => f(a)(c))
override def tryDecode(c: ACursor): Decoder.Result[B] = {
self.tryDecode(c).flatMap(a => f(a).tryDecode(c))
}
override def decodeAccumulating(c: HCursor): AccumulatingDecoder.Result[B] =
self.decodeAccumulating(c).andThen(result => f(result).decodeAccumulating(c))
}
查看这段代码,您可以看到,当您平面映射一个解码器时,您会看到一个新的解码器在相同的光标上运行:光标是解析操作的当前位置
在以下代码中:
implicit val paperDecoder: Decoder[Paper] = {
for {
title <- Decoder.decodeString
authors <- Decoder.decodeSet[PaperAuthor]
} yield Paper(title, authors)
}
解码器:解码器[纸张]={
为了{
标题
为了{
身份证件
implicit val paperDecoder: Decoder[Paper] = {
for {
title <- Decoder.decodeString
authors <- Decoder.decodeSet[PaperAuthor]
} yield Paper(title, authors)
}
implicit val paperDecoder: Decoder[Paper] = Decoder.instance(cursor => Xor.right(Paper("",Set.empty)))
implicit val paperViewDecoder: Decoder[PublishedPaperView] = Decoder.instance(
cursor =>
for {
id <- cursor.downField("id").as[PaperId]
paper <- cursor.downField("paper").as[Paper]
} yield PublishedPaperView(id, paper)
)