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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23531065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:18:00  来源:igfitidea点击:

Scala: Parse JSON directly into a case class

jsonscalaparsingscala-2.10case-class

提问by SRobertJames

Given a string of JSON, and a case class that corresponds to it, what's a simple way to parse the JSON into the case class? There are many libraries available, but it seems that Scala might now do this out of the box.

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

What about if the JSON should be parsed into a list of the case class?

如果 JSON 应该被解析为 case 类的列表呢?

UPDATE:

更新:

Jerkson seems to be abandoned, and I don't want to install the full Play or Lift framework or anything else heavy.

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

采纳答案by Andreas Neumann

There are several frameworks which can exactly do that.

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

circe

Used a lot nowdays. Many great features. Will pull cats in.

现在用的很多。许多很棒的功能。会拉猫进来。

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

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

JSON4s

JSON4s

JSON4s is quite mature and supports Hymansonor a nativeJSON-Parser. Used it in many projects to replace jerkson.

JSON4s 非常成熟,支持Hymanson原生JSON-Parser。在许多项目中使用它来代替 jerkson。

https://github.com/json4s/json4s

https://github.com/json4s/json4s

play-json

播放-json

Can be used without the full play stack. Great support as part of the play project at typesafe.

可以在没有完整播放堆栈的情况下使用。作为 typesafe 游戏项目的一部分的大力支持。

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

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

Scala-Pickling

Scala 酸洗

A serialization Framework. There is an option to serialize/ and deserialize to JSON.

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

https://github.com/scala/pickling

https://github.com/scala/pickling

Spray JSON

喷 JSON

Can searialize and deserialize. Need to know number of arguments for deserialization tough.

可以序列化和反序列化。需要知道反序列化困难的参数数量。

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

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

回答by dranxo

I've used https://github.com/json4s/json4s, only gripe so far is https://github.com/json4s/json4s/issues/137

我使用过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]

回答by Walker Rowe

Use spray-json as it is small.

使用 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]

Download spray-json into sbt using this build.sbt:

使用这个 build.sbt 将 Spray-json 下载到 sbt 中:

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

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

回答by Rjk

For anyone bumping into this for the first time, circeis also a good option

对于第一次遇到这个问题的人来说,circe也是一个不错的选择

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

回答by saket

Use net.liftweb

使用 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)

Make sure the Scala version matches the lift-json jar. For ex. for Scala 2.10 use lift-json_2.10.

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

回答by Gangstead

Spray Json is pretty light weight and does exactly what you need. It's a toolkit instead of a full on framework and you can just import the Spray-json project instead of the entire project.

Spray Json 非常轻巧,可以满足您的需求。它是一个工具包而不是完整的框架,您可以只导入 Spray-json 项目而不是整个项目。

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

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

The examples can get you set up very quickly. Most of the time your code to translate to/from JSON ends up being one liners, but you have the ability to explicitly handle it in case you have some weird requirements.

这些示例可以让您非常快速地进行设置。大多数情况下,您要转换为 JSON 或从 JSON 转换的代码最终都是一行代码,但是如果您有一些奇怪的需求,您可以明确地处理它。

回答by Adrian

I second the JSON conversion in the Play Framework.

我在 Play 框架中支持 JSON 转换。

Also take a look at Hymanson which is mature. Note you will need to use Hymanson Scala Module : https://github.com/FasterXML/Hymanson-module-scala.

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

A decent article providing an intro - then some code to add implicit conversions : https://coderwall.com/p/o--apg/easy-json-un-marshalling-in-scala-with-Hymanson

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