我有一个带有递归字段的json-schema (https://json-schema.org),我想以编程方式解析遵循Scala中的模式的json。
一种选择是使用Argus (https://github.com/aishfenton/Argus),但唯一的问题是它使用Scala宏,因此IntelliJ不支持使用该库的解决方案。
在Scala中执行这样的任务,最好是在IntelliJ上运行良好的任务,推荐的方式是什么?
发布于 2018-12-21 08:03:13
Circe是一个使用JSON的很棒的库。下面的示例使用semi automatic decoding。custom codecs还提供了automatic decoding和使用Circe的指南。
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))
}
}
发布于 2018-12-20 06:52:16
你有没有看过https://github.com/circe/circe,用类型化的格式解析Json已经很不错了。
发布于 2018-12-20 08:01:59
我不明白你说的递归字段是什么意思。但是有很多不同的库来解析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框架中工作)
如果你真的不想使用任何特殊的库,有人尝试在这里使用How to parse JSON in Scala using standard Scala classes?
https://stackoverflow.com/questions/53860225
复制相似问题