我需要在我的服务器上收到一个大的JSON(超过22个字段)。 我有一个包含很多字段的案例类:
case class Filters(objectType: Option[String] = None,
deal: Option[String] = None,
roomsCount: Option[String] = None,
region: Option[Int] = None,
district: Option[Int] = None,
direction: Option[Int] = None
...
)
控制器中的JSON格式功能:
implicit val filtersFormat = Json.format[Filters]
编译时我遇到错误:
[error] WebSockets.scala:18: No unapply or unapplySeq function found
[error] implicit val filtersFormat = Json.format[Filters]
[error] ^
有没有办法在不将JSON分解为小部件的情况下解决问题?
答案 0 :(得分:4)
正如@Sawyer提到的,您可以使用external library。摘自this blog。
首先将lib依赖项添加到您的SBT
libraryDependencies += "ai.x" %% "play-json-extensions" % "0.42.0"
然后您可以像这样使用它:
import ai.x.play.json.Jsonx
import play.api.libs.json.{Json, OFormat}
case class Foo(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)
object Foo {
implicit val f: OFormat[Foo] = Jsonx.formatCaseClass[Foo]
}
答案 1 :(得分:1)
我是这样做的:
case class Filters(part1: Part1, part2: Part2, ...)
case class Part1(
field1: Field1,
field2: Field2,
...
field10: Field10,
)
object Part1 {
implicit val part1Format = Json.format[Part1]
}
...
object Filters {
implicit val filtersReads = (
JsPath.read[Part1] and
JsPath.read[Part2] and
...
)(Filters.apply _)
implicit val filtersWrites = (
JsPath.write[Part1] and
JsPath.write[Part2] and
...
)(unlift(Filters.unapply))
}
答案 2 :(得分:0)
也可以选择手动执行,而不是使用格式,读取或写入:
implicit object JsFormatter extends Format[Filter] {
private val tagField1 = "field1"
private val tagField2 = "field2"
private val tagField3 = "field3"
...
private val tagFieldN = "fieldN" // N > 22
override def reads(json: JsValue): JsResult[Filter] = JsSuccess(
Filter(
(json \ tagField1).as[Long],
(json \ tagField2).as[Int],
(json \ tagField3).as[String],
...
(json \ tagFieldn).as[Boolean]
)
)
override def writes(filter: Filter): JsValue = Json.obj(
tagField1 -> filter.field1,
tagField2 -> filter.field2,
tagField3 -> filter.field3,
...
tagFieldN -> filter.fieldN
)
}
我们有很多从22列传递的案例类,所有案例类都可以正常工作而不会将它们分成几部分。
答案 3 :(得分:0)
我有相同的铅,并通过使用找到解决方案
Jsonx.formatCaseClass[Filters]