在 Scala 中基于具有递归字段的模式解析 JSON

Parsing JSON based off of schema with recursive fields in Scala

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

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

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

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

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

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

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

Circe is a great library for working with JSON. The following example uses semi automatic decoding. Circe also has guides for automatic decoding and for using custom 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))
  }

}