首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Circe解码对象的集合

使用Circe解码对象的集合
EN

Stack Overflow用户
提问于 2018-10-30 15:55:01
回答 1查看 1.8K关注 0票数 0

我有两门课看起来就像这样

代码语言:javascript
复制
import io.circe.Decoder

case class FactResponse(id: String, status: String) {
  ...
}


object FactResponse {

  implicit val decoder: Decoder[FactResponse] =
    Decoder.forProduct2("id", "status")(FactResponse.apply)

  def apply(json: String): FactResponse = {
    import io.circe.parser.decode
    decode[FactResponse](json).right.get
  }
}    



case class RuleEngineRequestResponse(content: Seq[Map[String, String]])

object RuleEngineRequestResponse {

  implicit val decoder: Decoder[RuleEngineRequestResponse] =
    Decoder.forProduct1("content")(RuleEngineRequestResponse.apply(_: String))

  def apply(json: String): RuleEngineRequestResponse = {
    import io.circe.parser.decode
    println("here")
    print(json)
    println(decode[RuleEngineRequestResponse](json).left.get)
    decode[RuleEngineRequestResponse](json).right.get
  }
}

我正试图解码一个类似于这样的json

{“内容”:{"id":"22",“状态”:“22”}

但是,我的解码失败是DecodingFailure(字符串,下行域(“内容”))

我不知道这里到底出了什么问题,json肯定是正确的,我甚至试图将内容解析成一系列的映射,但是,我还是一次又一次地得到了相同的东西。知道如何使用circe将嵌套对象解析为数组吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-30 17:57:47

我认为,如果让circe自动导出解码器,可以大大简化解码过程:

代码语言:javascript
复制
import io.circe.generic.auto._
import io.circe.parser.decode

case class FactResponse(id: String, status: String)
case class RuleEngineRequestResponse(content: Seq[FactResponse])

object Sample extends App {
  val testData1 =
    """
      |{
      |   "content":[
      |      {
      |         "id":"22",
      |         "status":"22"
      |      }
      |   ]
      |}""".stripMargin

  val testData2 =
    """
      |{
      |   "content":[
      |      {
      |         "id":"22",
      |         "status":"22"
      |      },
      |      {
      |         "id":"45",
      |         "status":"56"
      |      }
      |   ]
      |}""".stripMargin

  println(decode[RuleEngineRequestResponse](testData1))
  println(decode[RuleEngineRequestResponse](testData2))

}

这一产出如下:

代码语言:javascript
复制
Right(RuleEngineRequestResponse(List(FactResponse(22,22))))
Right(RuleEngineRequestResponse(List(FactResponse(22,22), FactResponse(45,56))))

您需要包含依赖项:

代码语言:javascript
复制
  "io.circe" %% "circe-generic" % circeVersion,
  "io.circe" %% "circe-parser"  % circeVersion,

我用过circe版本的0.10.0

你可以检查一下这里。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53068251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档