如何在 play 框架中处理一个大的 json 文件数据解析(超过22个 root variables)

基本算是半翻译一下Play Framework - Beginner Tutorial : How to handle a big json file in play ( more than 22 root variables)

今天工作碰到一个问题是一个 case class 要被转化成 json, 但是这个 case class 的参数超过22个了,长得像这个样子

1
2
3
4
5
6
case class JsonExample (
a1:String, a2:String, a3:String, a4:String, a5:String, a6:String,
a7:String, a8:String, a9:String, a10:String, a11:String, a12:String,
a13:String, a14:String, a15:String, a16:String, a17:String, a18:String,
a19:String, a20:String, a21:String, a22:String, a23:String, a24:String
)

通常我们会尝试使用这样的方式去很方便的通过Json.toJson(object)直接得到 json 数据

1
2
import play.api.libs.json._
implicit val jsonExampleFormat = Json.format[JsonExample]

不幸的是直接编译错误

1
2
3
<console>:16: error: No unapply or unapplySeq function found
implicit val jsonExampleFormat = Json.format[JsonExample]
^

解决方案有两个

第一种,使用 Play-Json extensions(requires play-json >= 2.4)

1
2
import ai.x.play.json.Jsonx
implicit val jsonExampleFormat = Jsonx.formatCaseClass[JsonExample]

第二种(推荐使用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
case class A (
a1:String, a2:String, a3:String, a4:String,
a5:String, a6:String, a7:String, a8:String
)

case class B (
a9:String, a10:String, a11:String, a12:String,
a13:String, a14:String, a15:String, a16:String
)
case class C (
a17:String, a18:String, a19:String, a20:String,
a21:String, a22:String, a23:String, a24:String
)
case class JsonExample2 (
a : A,
b : B,
c : C
)

import play.api.libs.json._
implicit val jsonAFormat : Format[A] = Json.format[A]
implicit val jsonBFormat : Format[B]= Json.format[B]
implicit val jsonCFormat : Format[C] = Json.format[C]

import play.api.libs.functional.syntax._
implicit val jsonExample2Format: Format[JsonExample2] = (
(JsPath).format[A] and
(JsPath).format[B] and
(JsPath).format[C]
)(JsonExample2.apply, unlift(JsonExample2.unapply))
月月说要给我打赏,就还是放了二维码,😝