在 Scala 中使用什么 JSON 库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8054018/
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 18:02:39  来源:igfitidea点击:

What JSON library to use in Scala?

jsonscala

提问by David Portabella

I need to build a JSON string, something like this:

我需要构建一个 JSON 字符串,如下所示:

[
  { 'id': 1, 'name': 'John'},
  { 'id': 2, 'name': 'Dani'}
]

val jArray = JsArray();
jArray += (("id", "1"), ("name", "John"))
jArray += (("id", "2"), ("name", "Dani"))
println(jArray.dump)

I need to be able to add rows to the jArray, something like jArray += ...

我需要能够向 中添加行jArray,例如jArray += ...

What is the closest library/solution to this?

最接近的图书馆/解决方案是什么?

回答by Alex Dean

Unfortunately writing a JSON library is the Scala community's version of coding a todo list app.

不幸的是,编写 JSON 库是 Scala 社区编写待办事项列表应用程序的版本。

There are quite a variety of alternatives. I list them in no particular order, with notes:

有很多种选择。我不按特定顺序列出它们,并附有注释:

  1. parsing.json.JSON- Warningthis library is available only up to Scala version 2.9.x (removed in newer versions)
  2. spray-json- Extracted from the Spray project
  3. Jerkson± - Warninga nice library (built on top of Java Hymanson) but now abandonware. If you are going to use this, probably follow the Scalding project's example and use the backchat.io fork
  4. sjson- By Debasish Ghosh
  5. lift-json- Can be used separately from the Lift project
  6. json4s§ ± - An extraction from lift-json, which is attempting to create a standard JSON AST which other JSON libraries can use. Includes a Hymanson-backed implementation
  7. Argonaut§ - A FP-oriented JSON library for Scala, from the people behind Scalaz
  8. play-json± - Now available standalone, see this answer for details
  9. dijon- A handy, safe and efficient JSON library, uses jsoniter-scalaunder hood.
  10. sonofjson- JSON library aiming for a super-simple API
  11. Jawn- JSON library by Erik Osheim aiming for Hymanson-or-faster speed
  12. Rapture JSON± - a JSON front-end which can use 2, 4, 5, 6, 7, 11 or Hymanson as back-ends
  13. circe- fork of Argonaut built on top of catsinstead of scalaz
  14. jsoniter-scala- Scala macros for compile-time generation of ultra-fast JSON codecs
  15. Hymanson-module-scala- Add-on module for Hymansonto support Scala-specific datatypes
  16. borer- Efficient CBOR and JSON (de)serialization in Scala
  1. parsing.json.JSON-警告此库仅适用于 Scala 版本 2.9.x(在较新版本中删除)
  2. Spray-json- 从 Spray 项目中提取
  3. Jerkson± -警告一个不错的库(建立在 Java Hymanson 之上)但现在放弃软件。如果你打算使用它,可能按照Scalding项目的例子并使用backchat.io fork
  4. sjson- 作者:Debasish Ghosh
  5. Lift -json- 可以与 Lift 项目分开使用
  6. json4s§ ± -从lift-json中提取,它试图创建一个其他JSON库可以使用的标准JSON AST。包括Hyman逊支持的实现
  7. 阿尔戈英雄§ - Scalaz 的面向 FP 的 JSON 库,来自 Scalaz 背后的人
  8. play-json± - 现在可独立使用,详情请参阅此答案
  9. dijon- 一个方便、安全和高效的 JSON 库,在底层使用jsoniter-scala
  10. sonofjson- 旨在提供超简单 API 的 JSON 库
  11. Jawn- Erik Osheim 的 JSON 库,旨在实现Hyman逊或更快的速度
  12. Rapture JSON± - 一个 JSON 前端,可以使用 2、4、5、6、7、11 或 Hymanson 作为后端
  13. - 建立在之上的 Argonaut 叉子,而不是 scalaz
  14. jsoniter-scala- 用于编译时生成超快速 JSON 编解码器的 Scala 宏
  15. Hymanson-module-scala- Hymanson 的附加模块以支持 Scala 特定的数据类型
  16. 蛀虫-高效CBOR和JSON(德)序列化的斯卡拉

= has not fixed security vulnerabilities, § = has Scalaz integration, ± = supports interop with Hymanson JsonNode

= 没有修复安全漏洞,§ = 有 Scalaz 集成,± = 支持与 Hymanson 的互操作 JsonNode

In Snowplowwe use json4s with the Hymanson back-end; we've had good experiences with Argonaut too.

除雪机,我们使用与Hyman逊后端json4s; 我们对 Argonaut 也有很好的体验。

回答by fmpwizard

Lift-json is at version 2.6 and it works really well (and is also very well supported, the maintainer is always ready to fix any bugs users may find. You can find examples using it on the github repository

Lift-json 是 2.6 版本,它运行得非常好(并且也得到了很好的支持,维护者随时准备修复用户可能发现的任何错误。您可以在github 存储库中找到使用它的示例

The maintainer (Joni Freeman) is always reachable on the Lift mailinglist. There are also other users on the mailing list who are very helpful as well.

维护者 (Joni Freeman) 始终可以在Lift 邮件列表中找到。邮件列表中还有其他用户也非常乐于助人。

As @Alexey points out, if you want to use the library with other Scala version, say 2.11.x, change scalaVersionand use %%as follows:

正如@Alexey 指出的那样,如果您想将该库与其他 Scala 版本一起使用,请按如下方式2.11.x更改scalaVersion和使用%%

scalaVersion := "2.11.5" 

"net.liftweb" %% "lift-json" % "2.6"

You can check the liftweb.netsite to find out the latest version as time goes by.

随着时间的推移,您可以查看liftweb.net站点以找出最新版本。

回答by paradigmatic

I suggest using jerkson, it supports most basic type conversions:

我建议使用jerkson,它支持最基本的类型转换:

scala> import com.codahale.jerkson.Json._

scala> val l = List( 
                 Map( "id" -> 1, "name" -> "John" ),
                 Map( "id" -> 2, "name" -> "Dani")
               )

scala> generate( l )

res1: String = [{"id":1,"name":"John"},{"id":2,"name":"Dani"}]

回答by Ramon

Number 7 on the list is Hymanson, not using Jerkson. It has support for Scala objects, (case classes etc).

名单上的第 7 位是Hyman逊,而不是使用Hyman森。它支持 Scala 对象(案例类等)。

Below is an example of how I use it.

下面是我如何使用它的示例。

object MyHymansonMapper extends HymansonMapper
val jsonString = MyHymansonMapper.serializeJson(myObject)
val myNewObject = MyHymansonMapper.deserializeJson[MyCaseClass](jsonString)

This makes it very simple. In addition is the XmlSerializer and support for JAXB Annotations is very handy.

这使它变得非常简单。此外是 XmlSerializer 和对 JAXB Annotations 的支持非常方便。

This blog post describes it's use with JAXB Annotations and the Play Framework.

这篇博文描述了它与 JAXB Annotations 和 Play Framework 的结合使用。

http://krasserm.blogspot.co.uk/2012/02/using-jaxb-for-xml-and-json-apis-in.html

http://krasserm.blogspot.co.uk/2012/02/using-jaxb-for-xml-and-json-apis-in.html

Here is my current HymansonMapper.

这是我目前的 HymansonMapper。

trait HymansonMapper {

  def jsonSerializer = {
    val m = new ObjectMapper()
    m.registerModule(DefaultScalaModule)
    m
  }

  def xmlSerializer = {
    val m = new XmlMapper()
    m.registerModule(DefaultScalaModule)
    m
  }

  def deserializeJson[T: Manifest](value: String): T = jsonSerializer.readValue(value, typeReference[T])
  def serializeJson(value: Any) = jsonSerializer.writerWithDefaultPrettyPrinter().writeValueAsString(value)
  def deserializeXml[T: Manifest](value: String): T = xmlSerializer.readValue(value, typeReference[T])
  def serializeXml(value: Any) = xmlSerializer.writeValueAsString(value)

  private[this] def typeReference[T: Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  private[this] def typeFromManifest(m: Manifest[_]): Type = {
     if (m.typeArguments.isEmpty) { m.erasure }
     else new ParameterizedType {
       def getRawType = m.erasure

       def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray

       def getOwnerType = null
     }
  }
}   

回答by Alex Povar

Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:

也许我有点晚了,但你真的应该尝试使用 play 框架中的 json 库。你可以看看文档。在当前的 2.1.1 版本中,您不能在没有完整播放 2 的情况下单独使用它,因此依赖项将如下所示:

val typesaferepo  = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
val play2 = "play" %% "play" % "2.1.1"

It will bring you whole play framework with all stuff on board.

它将为您带来包含所有内容的完整游戏框架。

But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-jsonfrom 2.2-snapshot.

但据我所知,来自 Typesafe 的人计划在 2.2 版本中将其分开。所以,有来自 2.2-snapshot 的独立play-json

回答by eugen

You should check Genson. It just works and is much easier to use than most of the existing alternatives in Scala. It is fast, has many features and integrations with some other libs (jodatime, json4s DOM api...).

你应该检查Genson。它只是有效并且比 Scala 中的大多数现有替代方案更容易使用。它速度很快,具有许多功能并与其他一些库(jodatime、json4s DOM api...)集成。

All that without any fancy unecessary code like implicits, custom readers/writers for basic cases, ilisible API due to operator overload...

所有这些都没有任何花哨的不必要的代码,例如隐式,基本情况的自定义读取器/写入器,由于运算符重载而导致的 ilisible API...

Using it is as easy as:

使用它就像:

import com.owlike.genson.defaultGenson_

val json = toJson(Person(Some("foo"), 99))
val person = fromJson[Person]("""{"name": "foo", "age": 99}""")

case class Person(name: Option[String], age: Int)

Disclaimer: I am Gensons author, but that doesn't meen I am not objective :)

免责声明:我是 Gensons 的作者,但这并不意味着我不客观:)

回答by Akavall

Here is a basic implementation of writing and then reading jsonfile using json4s.

这是json使用json4s.

import org.json4s._
import org.json4s.Hymanson.JsonMethods._
import org.json4s.JsonDSL._
import java.io._
import scala.io.Source


object MyObject { def main(args: Array[String]) {

  val myMap = Map("a" -> List(3,4), "b" -> List(7,8))

  // writing a file 
  val jsonString = pretty(render(myMap))

  val pw = new PrintWriter(new File("my_json.json"))
  pw.write(jsonString)
  pw.close()

  // reading a file 
  val myString = Source.fromFile("my_json.json").mkString
  println(myString)

  val myJSON = parse(myString)

  println(myJSON)

  // Converting from JOjbect to plain object
  implicit val formats = DefaultFormats
  val myOldMap = myJSON.extract[Map[String, List[Int]]]

  println(myOldMap)
 }
}

回答by Piohen

Rapture seems to be missing in the list of the answers. It can be obtained from http://rapture.io/and allows you (among other thing) to:

答案列表中似乎缺少 Rapture。它可以从http://rapture.io/获得,并允许您(除其他外):

  • select JSON back-end, which is very useful if you already use one (in import)
  • decide if you work with Try, Future, Option, Either, etc. (also in import)
  • do a lot of work in a single line of code.
  • 选择 JSON 后端,如果您已经使用了一个(在导入中),这将非常有用
  • 决定是否使用 Try、Future、Option、Either 等(也在导入中)
  • 在一行代码中完成大量工作。

I don't want to copy/paste Rapture examples from it's page. A nice presentation about Rapture's features was given by Jon Pretty at SBTB 2014: https://www.youtube.com/watch?v=ka5-OLJgybI

我不想从它的页面复制/粘贴 Rapture 示例。Jon Pretty 在 SBTB 2014 上做了一个关于 Rapture 功能的精彩演讲:https: //www.youtube.com/watch?v=ka5-OLJgybI

回答by HRJ

Jawnis a very flexible JSON parser library in Scala. It also allows generation of custom ASTs; you just need to supply it with a small trait to map to the AST.

Jawn是 Scala 中一个非常灵活的 JSON 解析器库。它还允许生成自定义 AST;你只需要为它提供一个小的特征来映射到 AST。

Worked great for a recent project that needed a little bit of JSON parsing.

非常适合最近需要一点 JSON 解析的项目。

回答by Bjorn

@AlaxDean's #7 answer, Argonautis the only one that I was able to get working quickly with sbt and intellij. Actually json4s also took little time but dealing with a raw AST is not what I wanted. I got argonaut to work by putting in a single line into my build.st:

@AlaxDean 的 #7 答案,Argonaut是唯一一个我能够快速使用 sbt 和 intellij 的人。实际上 json4s 也花费了很少的时间,但是处理原始 AST 并不是我想要的。我通过在 build.st 中加入一行来让 argonaut 工作:

libraryDependencies += "io.argonaut" %% "argonaut" % "6.0.1"

libraryDependencies += "io.argonaut" %% "argonaut" % "6.0.1"

And then a simple test to see if it I could get JSON:

然后是一个简单的测试,看看我是否可以得到 JSON:

package mytest


import scalaz._, Scalaz._
import argonaut._, Argonaut._

object Mytest extends App {

  val requestJson  =
    """
    {
      "userid": "1"
    }
    """.stripMargin

  val updatedJson: Option[Json] = for {
    parsed <- requestJson.parseOption
  } yield ("name", jString("testuser")) ->: parsed

  val obj = updatedJson.get.obj
  printf("Updated user: %s\n", updatedJson.toString())
  printf("obj : %s\n", obj.toString())
  printf("userid: %s\n", obj.get.toMap("userid"))
}

And then

进而

$ sbt
> run
Updated user: Some({"userid":"1","name":"testuser"})
obj : Some(object[("userid","1"),("name","testuser")])
userid: "1"

Make sure you are familiar with Optionwhich is just a value that can also be null (null safe I guess). Argonaut makes use of Scalazso if you see something you don't understand like the symbol \/(an or operation) it's probably Scalaz.

确保您熟悉Option,它只是一个也可以为 null 的值(我猜是 null 安全的)。Argonaut 使用了Scalaz,因此如果您看到一些您不理解的符号\/(一个或操作),则可能是 Scalaz。