【问题标题】:How to define a `Write` for an case class which will generate nested custom fields?如何为将生成嵌套自定义字段的案例类定义“写入”?
【发布时间】:2014-04-17 06:00:56
【问题描述】:

Play 框架提供了一些 DSL 来读写 JSON,例如

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

case class User(name:String, age:Option[Int])

implicit val userWrites = (
  (__ \ "name" ).write[String] and
  (__ \ "age"  ).writeNullable[Int]
  )(unlift(User.unapply))

val user= new User("Freewind", Some(100))
Json.toJson(user)

它会生成一个json:

{"name":"Freewind","age":100}

但是如何定义userWrites来生成这样的JSON:

{
   "name" : "Freewind",
   "age"  : 100,
   "nested" : {
       "myname" : "Freewind",
       "myage"  :  100
   }
}

我尝试了一些解决方案,但没有一个可以工作。

【问题讨论】:

    标签: json playframework dsl


    【解决方案1】:

    您可以使用JSON transformers 实现这一点,如下代码所示:

    object Test {
    
      def main(args: Array[String]): Unit = {
    
        import play.api.libs.json._
        import play.api.libs.json.Reads._
        import play.api.libs.functional.syntax._
    
        case class User(name: String, age: Option[Int])
    
        implicit val userWrites = (
          (__ \ "name").write[String] and
          (__ \ "age").writeNullable[Int])(unlift(User.unapply))
    
        val jsonTransformer = (__).json.update(
          __.read[JsObject].map { o => o ++ Json.obj("nested" -> Json.obj()) }) and
          (__ \ 'nested).json.copyFrom((__).json.pick)      reduce
        
        val user = new User("Freewind", Some(100))
        val originalJson = Json.toJson(user)
        println("Original: " + originalJson)
        val transformedJson = originalJson.transform(jsonTransformer).get
        println("Tansformed: " + transformedJson)
    
      }
    
    }
    

    输出是这样的:

    原文:{"name":"Freewind","age":100}

    转换:{"name":"Freewind","age":100,"nested":{"name":"Freewind","age":100}}

    【讨论】:

    • 我不得不说这段代码真的很难阅读,但感谢您提供有效的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    相关资源
    最近更新 更多