【问题标题】:No Json serializer found for type Seq[(String, String)]. Try to implement an implicit Writes or Format for this type未找到 Seq[(String, String)] 类型的 Json 序列化程序。尝试为此类型实现隐式写入或格式
【发布时间】:2014-09-05 07:56:18
【问题描述】:

我想使用 Scala 将Seq[(String, String)] 转换为 JSON,但我遇到了这个错误:

找不到类型 Seq[(String, String)] 的 Json 序列化程序。尝试为此类型实现隐式写入或格式。

我该如何解决这个问题?

【问题讨论】:

    标签: json scala playframework-2.2


    【解决方案1】:

    这取决于您要达到的目标。假设您有这样的Seq[(String, String)]

    val tuples = Seq(("z", "x"), ("v", "b"))
    

    如果您尝试将其序列化如下:

    {
      "z" : "x",
      "v" : "b"
    }
    

    然后只需使用Json.toJson(tuples.toMap)。如果您想对元组进行一些自定义表示,您可以按照编译器的建议定义 Writes

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

    编辑

    import play.api.mvc._
    import play.api.libs.json._
    
    class MyController extends Controller {
      implicit val writer = new Writes[(String, String)] {
        def writes(t: (String, String)): JsValue = {
          Json.obj("something" -> t._1 + ", " + t._2)
        }
      }
    
      def myAction = Action { implicit request =>
        val tuples = Seq(("z", "x"), ("v", "b"))
        Ok(Json.toJson(tuples))
      }
    }
    

    【讨论】:

    • 感谢您的回复 serejja,但我想知道如何准备我的控制器以序列化 json 格式的 Seq[(String,String)]。
    • 请给我更多细节
    • @lotfitounsi 请查看我编辑的答案。这应该可以正常工作
    【解决方案2】:

    如果您想将 Scala 元组序列化为 2 元素 JSON 数组(这很常见),那么您可以为 2 元组 (A, B) 的一般情况编写一个隐式 Writes 对象。这将处理您的 (String, String) 以及任何其他类型组合的情况!

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

    如果你把它放在一个包对象中,它将对整个包可见。这是在许多类(即整个应用程序)中获得一致行为的好方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多