gpt4 book ai didi

scala - 在没有嵌套案例类的情况下使用 Spray Json 解析超过 22 个字段

转载 作者:行者123 更新时间:2023-12-01 12:09:09 27 4
gpt4 key购买 nike

我正在尝试使用 Spray-JSON 来编码包含超过 22 个字段的传入 JSON。由于没有 JsonFormat23() 方法,我不得不嵌套我的案例类以绕过限制。但是,传入的 JSON 不知道嵌套结构。

有没有办法避免在 Spray Json 中使用嵌套结构?

编辑

这是我的解决方案,以便其他人不会有同样的痛苦。我的一个问题是我所有的字段都是可选的,这增加了另一层复杂性。您可以在此解决方案中放置任意数量的字段

    implicit object myFormat extends RootJsonFormat[myFormat] {
override def write(js : myFormat):JsValue =
JsObject(
List(
Some("language" -> js.language.toJson),
Some("author" -> js.author.toJson),
....
).flatten: _*
)

override def read(json: JsValue):myFormat= {
val fieldNames = Array("language", ... , "author")

val jsObject = json.asJsObject
jsObject.getFields(fieldNames:_*)

// code to transform fields to case class

// Initializes class with list of parameters
myFormat.getClass.getMethods.find(x => x.getName == "apply" && x.isBridge)
.get.invoke(myFormat, mylist map (_.asInstanceOf[AnyRef]): _*).asInstanceOf[myFormat]

}
}

最佳答案

您可以按照 here 所述实现 RootJsonFormat解决 Tupple22Function22 限制。案例类中的 22 参数不再有限制(注意事项),因此您可以保持类结构平坦。在实现 RootJsonFormat 时,您甚至不必使用案例类作为目标反序列化类型,它可以是一个常规类。

请注意,即使您可以将 JSON 解析为案例类,您的代码中可能还会遇到 22 的其他限制。参见 this解释。例如,您获得了案例类,现在想将其保存到数据库中,如果没有自定义序列化程序,您的数据库框架将无法解决 22 参数限制。在这种情况下,转换为嵌套案例类可能会更简单。

在 Dotty 中,22 的限制将完全是 gone ,但这需要一些时间:

The limit of 22 for the maximal number of parameters of function types has been dropped. Functions can now have an arbitrary number of parameters. Functions beyond Function22 are represented with a new trait scala.FunctionXXL.

The limit of 22 for the size of tuples is about to be dropped. Tuples will in the future be represented by an HList-like structure which can be arbitrarily large.

关于scala - 在没有嵌套案例类的情况下使用 Spray Json 解析超过 22 个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com