【问题标题】:Parsing JSON based off of schema with recursive fields in Scala在 Scala 中使用递归字段解析基于模式的 JSON
【发布时间】:2018-12-19 22:46:47
【问题描述】:

我有一个带有递归字段的 json 模式 (https://json-schema.org),我想以编程方式解析符合 Scala 模式的 json。

一种选择是使用 Argus (https://github.com/aishfenton/Argus),但唯一的问题是它使用 Scala 宏,因此 IntelliJ 不支持使用此库的解决方案。

在 Scala 中执行此类任务的推荐方法是什么,最好是与 IntelliJ 配合良好的方法?

【问题讨论】:

    标签: json scala intellij-idea jsonschema scala-macros


    【解决方案1】:

    Circe 是一个很好的处理 JSON 的库。以下示例使用semi automatic decoding。 Circe 还有automatic decodingcustom codecs 使用指南。

    import io.circe.Decoder
    import io.circe.parser.decode
    import io.circe.generic.semiauto.deriveDecoder
    
    object Example {
    
      case class MyClass(name: String, code: Int, sub: MySubClass)
      case class MySubClass(value: Int)
      implicit val myClassDecoder:    Decoder[MyClass]    = deriveDecoder
      implicit val mySubClassDecoder: Decoder[MySubClass] = deriveDecoder
    
      def main(args: Array[String]): Unit = {
        val input = """{"name": "Bob", "code": 200, "sub": {"value": 42}}"""
        println(decode[MyClass](input).fold(_ => "parse failed", _.toString))
      }
    
    }
    

    【讨论】:

    • Circe 确实支持递归字段,它解决了我们的问题。谢谢!
    【解决方案2】:

    你看过https://github.com/circe/circe吗,用类型化的格式解析Json还是不错的。

    【讨论】:

      【解决方案3】:

      我不知道你对递归字段的意思。但是有很多不同的库用于解析 json。你可以使用lift-json
      https://github.com/lift/framework/tree/master/core/json

      这似乎很受欢迎,至少从我在 Stackoverflow 上看到的情况来看是这样。但我个人很喜欢 play.json
      https://www.playframework.com/documentation/2.6.x/ScalaJson#Json
      (另外,我使用 IntelliJ 并在 Play-framework 中工作)

      如果您真的不想使用任何特殊库,这里有人尝试这样做 How to parse JSON in Scala using standard Scala classes?

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        相关资源
        最近更新 更多