是否可以使用 json4s 将 JSON 数组解析为元组?

Is it possible to parse JSON array into a tuple with json4s?

举个例子:

import org.json4s.native.JsonMethods._
import org.json4s._

implicit val formats = DefaultFormats

case class A(name: String)
case class B(age: Int)
val json = parse("""[ {"name": "mark"}, { "age": 27 }, 5 ]""")
json.extract[Tuple3[A, B, Int]]

这个错误:

org.json4s.package$MappingException: No usable value for _1 No usable value for name Did not find value which can be converted into java.lang.String

Json4s scalaz 似乎有元组支持。我不确定在 json4s 中是否有任何内置的方法可以做到这一点。我通常这样解决这个问题

implicit val formats = DefaultFormats

class MySerializer extends CustomSerializer[Tuple3[A,B,Int]](format => (
    {
        case JArray(x :: y :: z :: Nil ) => {
                ( x.extract[A], y.extract[B], z.extract[Int])}
    },
    {
        case x:Tuple3[A,B,Int] => null
    }
))

然后根据你的代码做这样的事情

implicit val formats = DefaultFormats + new MySerializer
val json = parse("""[ {"name": "mark"}, { "age": 27 }, 5 ]""")
json.extract[Tuple3[A,B,Int]]