小编Dan*_*iel的帖子

使用scala argonaut编码嵌套类

我正在尝试编码/解码以下案例类

case class Person(name: String, age: Int, childs: List[Person])
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

object Person {
    implicit def PersonCodecJson =
        casecodec3(Person.apply, Person.unapply)("name", "age", "childs")

}
Run Code Online (Sandbox Code Playgroud)

与argonaut,但我得到以下编译器错误:

could not find implicit value for evidence parameter of type argonaut.EncodeJson[List[Person]]
Run Code Online (Sandbox Code Playgroud)

显然,编译器不知道如何处理List [Person]的编码,因为它在如何编码Person的定义中使用.

是否有一种聪明的方式告诉argonaut如何以正确的方式对其进行编码?

更新:感谢Travis:现在正在编译,但它无法正常工作.

implicit def PersonCodecJson : CodecJson[Person] =
        casecodec3(Person.apply, Person.unapply)("name", "age", "childs")
Run Code Online (Sandbox Code Playgroud)

导致无限递归和尝试解码的堆栈溢出

val input = """
    [{"name": "parent1", "age": 31, "childs": [{"name": "child1", "age": 2, "childs": []}]},
     {"name": "parent2", "age": 29, "childs": []}
    ]
    """
val persons = input.decodeOption[List[Person]].getOrElse(Nil)
Run Code Online (Sandbox Code Playgroud)

结果是

at Person$.PersonCodecJson(main.scala:8) …
Run Code Online (Sandbox Code Playgroud)

scala argonaut

9
推荐指数
1
解决办法
2081
查看次数

标签 统计

argonaut ×1

scala ×1