【问题标题】:json deserialize of ListBuffer[(String,String)] in play framework播放框架中 ListBuffer[(String,String)] 的 json 反序列化
【发布时间】:2014-01-13 04:41:38
【问题描述】:

我正在使用 scala 中的播放框架开发应用程序,我想要 json 中的响应,但是如何做到编译时错误即将到来

 No Json deserializer found for type List[(String, String)]. Try to implement an implicit Writes or Format for this type.

列表缓冲区是

ListBuffer((This,a choke), (a Cv,15.6 gal))

我也这样做了

Json.toJson(list))

但仍然出现错误。

任何人给我一些想法来解决这个问题。

【问题讨论】:

    标签: json scala playframework playframework-2.1 playframework-2.2


    【解决方案1】:

    您希望它是(String, String) 的什么 json 表示形式? 如果是这样的:

    yourListName : {
      "1" : "2",
      "3" : "4"
    }
    

    那么你可以使用Json.toJson(list.toMap)。否则,您必须像这样为(String, String) 定义Writes

    implicit val writer = new Writes[(String, String)] {
        def writes(c: (String, String)): JsValue = {
          Json.obj("something" -> c._1 + ", " + c._2)
          //or like this:
          //Json.obj(c._1 -> c._2)
        }
      }
    

    一定要让这个作家在范围内

    【讨论】:

    • 你能帮我解决这个问题吗No Json deserializer found for type Map[String,Any]. Try to implement an implicit Writes or Format for this type. Map(sentence2 -> Map("UOM " -> List(Map(This -> a choke Cv equal to 15.6 gal/min psi½), Map(This -> 15.6 gal/min psi½), Map(This -> 120 bara,), Map(This -> 110 gal/min psi½), Map(This -> 120 bara.), Map(a choke Cv -> a choke Cv equal to 15.6 gal/min psi½), Map(a choke Cv -> 15.6 gal/min psi½), 这类数据
    【解决方案2】:

    正如这个线程中所讨论的[2.1] Json.format macros and Tuple2play-json 2.1 还不支持元组,主要是因为 json 不支持元组。如果您希望将元组写为数组,则可以对元组使用隐式格式:

    implicit def tuple2Writes[A, B](implicit aWrites: Writes[A], bWrites: Writes[B]): Writes[Tuple2[A, B]] = new Writes[Tuple2[A, B]] {
      def writes(tuple: Tuple2[A, B]) = JsArray(Seq(aWrites.writes(tuple._1), bWrites.writes(tuple._2)))
    }
    

    【讨论】:

      【解决方案3】:

      您可以在一行中执行此操作,只需隐式声明即可:

      implicit def tuple2[A : Writes, B : Writes] = Writes[(A, B)] ( t =>  Json.obj("something1" -> t._1, "something1" -> t._2) )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 2014-02-08
        • 1970-01-01
        • 1970-01-01
        • 2017-01-15
        相关资源
        最近更新 更多