Search code examples
scalajson4s

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


Take the following example:

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]]

This errors out:

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


Solution

  • Json4s scalaz seems to have tuple support. I am not sure if there is any built in way to do this in json4s. I generally solved this issue something like this

    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
        }
    ))
    

    And then from your code do something like this

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