我正在尝试为案例类编写一个读/写值,其中许多值可能为null。按照Play Framework的教程,我将其写为
implicit val incomingMessageWrites: Writes[IncomingMessage] = (
(JsPath \ "stageNum").write[Int] and
(JsPath \ "stage").write[String] and
(JsPath \ "stageTime").write[Long] and
(JsPath \ "vendorId").write[String] and
(JsPath \ "text").writeNullable[String] and
(JsPath \ "campaignCode").writeNullable[String] and
(JsPath \ "osTotals").writeNullable[OSTotals] and
(JsPath \ "splitSegment").writeNullable[Int] and
(JsPath \ "segmentNum").writeNullable[Int] and
(JsPath \ "osBatchStatus").writeNullable[OSBatchStatus]
)(unlift(IncomingMessage.unapply))
然而,我一直遇到同样的问题,IntelliJ告诉我,由于“应用程序不接受参数”,因此提升方法不起作用。
案例类是
case class IncomingMessage(
stageNum: Int,
stage: String,
stageTime: Long,
vendorId: String,
text: String,
campaignCode: String,
osTotals: OSTotals,
splitSegment: Int,
segmentNum: Int,
osBatchStatus: OSBatchStatus) {
def this(stageNum: Int, stage: String, stageTime: Long, vendorId: String, text: String, campaignCode: String) =
this(stageNum, stage, stageTime, vendorId, text, campaignCode, null, 0, 0, null)
def this(stageNum: Int, stage: String, stageTime: Long, splitSegment: Int, vendorId: String, text: String, campaignCode: String) =
this(stageNum, stage, stageTime, vendorId, text, campaignCode, null, splitSegment, 0, null)
def this(stageNum: Int, stage: String, stageTime: Long, segmentNum: Int, vendorId: String) =
this(stageNum, stage, stageTime, vendorId, null, null, null, 0, segmentNum, null)
def this(stageNum: Int, stage: String, stageTime: Long, segmentNum: Int, vendorId: String, osTotals: OSTotals) =
this(stageNum, stage, stageTime, vendorId, null, null, osTotals, 0, segmentNum, null)
def this(stageNum: Int, stage: String, stageTime: Long, vendorId: String, oSBatchStatus: OSBatchStatus) =
this(stageNum, stage, stageTime, vendorId, null, null, null, 0, 0, osBatchStatus)
}
其他案例类
也会发生同样的事情case class OSBatchStatus(os: String, success: Int, failure: Int)
object OSBatchStatus {
implicit val oSBatchStatusReads: Reads[OSBatchStatus] = (
(JsPath \ "os").readNullable[String] and
(JsPath \ "success").readNullable[Int] and
(JsPath \ "failure").readNullable[Int]
)(OSBatchStatus.apply _)
}
我写了读写值,但省略了它们以节省空间。
非常感谢任何和所有帮助。
答案 0 :(得分:2)
如果输入JSON文件中有可选字段,那么案例类的相应字段也应该是可选的。您对Reads
OSBatchStatus
的定义假定所有字段都是可选字段,因此您的案例类应如下所示:
case class OSBatchStatus(os: Option[String], success: Option[Int], failure: Option[Int])
相同的规则适用于您的IncomingMessage
案例类(四个字段是强制性的,其他字段应为Option[T]
)。此外,由于JSON文件中的字段与案例类中的字段具有完全相同的名称,因此您可以使用将为您自动生成Reads/Writes/Format
的play-json方法:
import play.api.libs.functional.syntax._
import play.api.libs.json._
implicit val incomingMessageWrites = Json.writes[IncomingMessage]
implicit val osBatchStatusReads = Json.reads[OSBatchStatus]
implicit val osTotalsFormat = Json.format[OSTotals] // Will generate both `Reads` and `Writes`