【问题标题】:Parsing two kinds of json with one case class?用一个案例类解析两种json?
【发布时间】:2019-04-01 18:45:41
【问题描述】:

我在 scala 中有一个需要解析 json 对象的案例类。然而,json 对象可以有两种不同的外观。像这样:

 "hint": {
            "structure": [
               "HIDE"
            ]
         }

或者像这样:

"hint": {
          "type": "1",
          "template": "A"
        }

我想使用 circe 将它们都解析到 Scala 中的同一个案例类中。我试过做这样的事情:

case class Hint(`type`:Option[String] = None,template:Option[String], structure: Option[List[String]])

object Hint {
        implicit val hintJsonDecoder: Decoder[Hint] = deriveDecoder[Hint]
      implicit val hintJsonEncoder: ObjectEncoder[Hint] = deriveEncoder[rHint]

}

但似乎应该有一种更简洁的方法来执行此操作,这样我就可以在第一个实例的情况下返回一个字符串列表,在第二个实例中只返回类型和模板。但我不知道如何使用 Circe 来做到这一点。

感谢您的帮助!

【问题讨论】:

    标签: scala circe


    【解决方案1】:

    也许我不明白你的问题,但 Option 的使用给了你你不想要的东西。如果您想要一个不那么冗长的解决方案,您可以使用自动派生,如下所示:

    import io.circe.generic.auto._
    import io.circe.parser.decode
    
    case class HintContainer(hint: Hint)
    case class Hint(`type`: Option[String], template: Option[String], structure: Option[List[String]])
    
    object Sample extends App {
      val testData1 =
        """
          |{
          | "hint": {
          |     "structure": [
          |         "HIDE"
          |     ]
          | }
          |}
          |""".stripMargin
    
      val testData2 =
        """
          |{
          | "hint": {
          |     "type": "1",
          |     "template": "A"
          | }
          |}
          |""".stripMargin
    
      println(decode[HintContainer](testData1))
      println(decode[HintContainer](testData2))
    
    }
    

    这给出了:

    Right(HintContainer(Hint(None,None,Some(List(HIDE)))))
    Right(HintContainer(Hint(Some(1),Some(A),None)))
    

    【讨论】:

      猜你喜欢
      • 2014-06-25
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2019-01-18
      • 2021-09-10
      相关资源
      最近更新 更多