1
votes

I am trying to use json4s to parse json string into object but even after running this code i am getting following as print result.

JObject(List((numbers,JArray(List(JInt(1), JInt(2), JInt(3), JInt(4))))))

    def main(args: Array[String]): Unit = {

        val json = """{"users": [
                       {"name": "Foo", "emails": ["[email protected]", "[email protected]"]},
                       {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}]
                     }"""
        val obj = parse(json).extract[List[User]]
        println(obj)
      }

    case class User(name: String, emails: List[String])
    case class UserList(users: List[User]) {
    override def toString(): String = {
       this.users.foldLeft("")((a, b) => a + b.toString)
    }
}

Please help

1

1 Answers

3
votes

Just add implicit val formats = DefaultFormats and change the genric type to UserList :

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

object Test {
       def main(args: Array[String]): Unit = {
           implicit val formats = DefaultFormats
           val json = """{"users": [
                   {"name": "Foo", "emails": ["[email protected]", "[email protected]"]},
                   {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}]
                 }"""

           val obj = parse(json).extract[UserList]
           println(obj)
       }
}
case class User(name: String, emails: List[String])
case class UserList(users: List[User])

and the output is:

UserList(List(User(Foo,List([email protected], [email protected])), User(Bar,List([email protected], [email protected]))))