【问题标题】:How to convert a json value "aaa,bbb" to a "Seq[String]" with argonaut?如何使用 argonaut 将 json 值“aaa,bbb”转换为“Seq[String]”?
【发布时间】:2014-09-19 02:45:31
【问题描述】:

我正在使用 argonaut 将 json 解析为案例类。

json:

{
    "name" : "Mike",
    "email" : "a@aaa.com, b@bbb.com"
}

斯卡拉:

case class User(agentName: String, emails: Seq[String])

object User {
  implicit def DecodeJson: DecodeJson[User] =
    casecodec2(User.apply, User.unapply)("name", "email")
}

代码无法编译,错误是:

Error:(17, 65) could not find implicit value for evidence parameter of type        
    argonaut.EncodeJson[Seq[String]]
    casecodec2(User.apply, User.unapply)("name", "email")

如何解决它,以便我可以将 a@aaa.com, b@bbb.com 解析为 Seq("a@aaa.com", "b@bbb.com")

【问题讨论】:

    标签: json scala argonaut


    【解决方案1】:

    casecodec2 的参数是函数,所以如果你需要在解析后的 JSON 上执行这样的操作,你可以在那里进行:

    case class User(agentName: String, emails: Seq[String])
    
    object User {
      implicit val CodecJson: CodecJson[User] = casecodec2[String, String, User](
        (n, e) => User(n, e.split(", ")),
        u => Some((u.agentName, u.emails.mkString(", ")))
      )("name", "email")
    }
    

    或者,如果你真的只需要解码器:

    object User {
      implicit def DecodeJson: DecodeJson[User] =
        jdecode2L((n: String, e: String) => User(n, e.split(", ")))("name", "email")
    }
    

    casecodecN 是为了方便与案例类构造函数和提取器一起使用而设计的,但它比这更灵活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多