繁体   English   中英

Scala:将JSON直接解析为案例类

[英]Scala: Parse JSON directly into a case class

给定一个JSON字符串和一个与之对应的case类,将JSON解析为case类的简单方法是什么? 有许多可用的库,但是似乎Scala现在可以立即使用。

如果应该将JSON解析为case类的列表怎么办?

更新:

Jerkson似乎被遗弃了,我不想安装完整的Play或Lift框架或其他任何笨重的东西。

有几个框架可以完全做到这一点。

如今已使用很多。 许多强大的功能。 将猫拉进来。

https://circe.github.io/circe/ https://github.com/circe/circe

JSON4s

JSON4s已经相当成熟,并且支持jackson本地 JSON-Parser。 在许多项目中都用它代替了jerkson。

https://github.com/json4s/json4s

播放json

无需完整播放堆栈即可使用。 作为typesafe的play项目的一部分,提供了大力支持。

http://www.playframework.com/documentation/2.0/ScalaJson

斯卡拉酸洗

序列化框架。 有一个选项可以序列化/反序列化为JSON。

https://github.com/scala/pickling

喷JSON

可以海化和反序列化。 需要知道许多反序列化的论点很难。

https://github.com/spray/spray-json

我使用过https://github.com/json4s/json4s ,到目前为止唯一令人讨厌的是https://github.com/json4s/json4s/issues/137

import org.json4s._
import org.json4s.native.JsonMethods._

implicit val formats = DefaultFormats

case class ParsedPage(crawlDate: String, domain:String, url:String, text: String)

val js = """ {
"crawlDate": "20150226",
"domain": "0x20.be",
"url": "http://0x20.be/smw/index.php?title=99_Bottles_of_Beer&oldid=6214",
"text": "99 Bottles of Beer From Whitespace (Hackerspace Gent) Revision as of 14:43, 8 August 2012 by Hans ( Talk | contribs ) 99 Bottles of Beer Where: Loading map... Just me, with 99 bottles of beer and some friends. Subpages"
}"""


parse(js).extract[ParsedPage]

请使用spray-json,因为它很小。

import spray.json._
import DefaultJsonProtocol._


val json = """{"one" : "1", "two" : "2", "three" : "3"}""".parseJson

case class Numbers(one: String, two: String, three: String)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val numbersFormat = jsonFormat3(Numbers)

}

import MyJsonProtocol._

val converted = json.convertTo[Numbers]

使用以下build.sbt将spray-json下载到sbt中:

lazy val root = (project in file(".")). settings( name := "jsonExample", libraryDependencies += "io.spray" %% "spray-json" % "1.3.2" )

使用net.liftweb

import net.liftweb.json._
case class Detail(username:String, password:String)
implicit val formats = DefaultFormats
val input = parse(jsonString).extract[Detail]
println(input.username)

确保Scala版本与lift-json jar匹配。 对于前。 对于Scala 2.10,请使用lift-json_2.10。

对于初次接触此功能的人来说, 绕圈也是一个不错的选择

val customerJson = s"""{"id" : "1", "name" : "John Doe"}"""
case class Customer(id: String, name: String)
val customer = decode[Customer](customerJson)

Spray Json重量很轻,可以满足您的需求。 这是一个工具包,而不是完整的框架,您可以仅导入Spray-json项目而不是整个项目。

https://github.com/spray/spray-json

这些示例可以帮助您快速设置。 在大多数情况下,与JSON相互转换的代码最终只是一种衬里,但是如果您有一些奇怪的要求,则可以显式地处理它。

我第二次将Play框架中的JSON转换。

还要看看成熟的杰克逊。 请注意,您将需要使用Jackson Scala模块: https : //github.com/FasterXML/jackson-module-scala

一篇体面的文章提供了介绍-然后提供了一些代码以添加隐式转换: https//coderwall.com/p/o--apg/easy-json-un-marshalling-in-scala-with-jackson

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM