3

我正在学习斯卡拉。我试图找到一种将 JSON 字符串转换为 Scala 案例类实例的简单方法。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 如此复杂?为什么我要编写阅读器/编写器来序列化/反序列化简单的案例类实例?有没有简单的方法可以使用 play json api 转换案例类实例 -> json -> 案例类实例?

4

2 回答 2

3

假设你有

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

您可以通过以下方式在 Play 中轻松为此编写格式化程序

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!
于 2016-04-25T12:14:06.703 回答
1

查看uPickle

这是一个小例子:

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

val ex = Example("Hello", 3)

write(ex) // { "firstField": "Hello", "secondIntField" : 3 }
于 2016-04-25T12:12:10.067 回答