如何使用 play json 将具有单个值的 json 转换为大小写 class

How to convert a json with a single value to a case class using play json

我无法找到如何将具有单个值的 json 文档转换为案例 class。这是 json:

{
  "ax" : {
           "bx" : "value1",
           "by" : "value2
         }
}

这里是案例classes:

case class B(bx: String, by: String)
case class A(ax: B)

下面是读物:

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

object Implicits {
     implicit val bReads: Reads[B] = (
        ( __ \ "bx" ).read[String] ~
        ( __ \ "by" ).read[String]
     ) ( B.apply _ )    

     implicit val aReads: Reads[A] = (
        ( __ \ "ax" ).read[B]
     ) ( A.apply _ )
}

第二个隐式未编译并出现以下错误:

Error:(X, Y) overloaded method value read with alternatives:
(t: B)play.api.libs.json.Reads[B] <and>
(implicit r: play.api.libs.json.Reads[B])play.api.libs.json.Reads[B]
cannot be applied to ((B, Option[String]) => A)
   ( __ \ "ax" ).read[B] 

为了让它工作,我需要将 A class 更改为另一个值:

case class A(ax: B, temp: Option[String])

隐式读取:

implicit val aReads: Reads[A] = (
   ( __ \ "ax" ).read[B] ~
   ( __ \ "temp" ).readNullable[String]
) ( A.apply _ )

如何在不向 classes 添加不存在的内容的情况下完成读取?有什么想法吗?

单个参数案例 class 的 Reads 实例在 Play JSON 中有点笨拙,但以下应该有效

 implicit val reads: Reads[A] =
    (JsPath \ "ax").read[B].map(A.apply)