Scala 类 Gson 库

Gson-like library for scala

我正在学习 Scala。我试图找到一种简单的方法将 JSON String 转换为 Scala case class 实例。 Java 有很棒的库,叫做 Google Gson。它可以将 java bean 转换为 json 并且不需要一些特殊的编码,基本上你可以在一行代码中完成。

public class Example{
  private String firstField
  private Integer secondIntField

  //constructor

  //getters/setters here
}
//Bean instance to Json string
String exampleAsJson = new Gson().toJson(new Example("hehe", 42))

//String to Bean instance
Example exampleFromJson = new Gson().fromJson(exampleAsJson, Example.class)

我正在阅读有关 https://www.playframework.com/documentation/2.5.x/ScalaJson 的文章,但无法理解:为什么 scala 如此复杂?为什么我应该写 readers/writers 到 serialize/deserialize 普通简单案例 class 实例?是否有使用 play json api 转换 case class 实例 -> json -> case class 实例的简单方法?

查看uPickle

这是一个小例子:

case class Example(firstField: String, secondIntField: Int)

val ex = Example("Hello", 3)

write(ex) // { "firstField": "Hello", "secondIntField" : 3 }

假设你有

case class Foo(a: String, b: String)

您可以通过

在 Play 中轻松地为此编写一个 formatter
implicit val fooFormat = Json.format[Foo]

这将允许您序列化和反序列化到 JSON。

val foo = Foo("1","2")
val js = Json.toJson(foo)(fooFormat)  // Only include the specific format if it's not in scope.
val fooBack = js.as[Foo]              // Now you have foo back!