无法使用json4s scala将json转换为对象

时间:2015-05-18 18:43:12

标签: json scala jackson json4s

我正在尝试使用json4s将json字符串解析为对象,但即使在运行此代码后,我也会将其作为打印结果。

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": ["Foo@gmail.com", "foo2@gmail.com"]},
                       {"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}]
                     }"""
        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)
    }
}

请帮忙

1 个答案:

答案 0 :(得分:3)

只需添加implicit val formats = DefaultFormats并将genric类型更改为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": ["Foo@gmail.com", "foo2@gmail.com"]},
                   {"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}]
                 }"""

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

,输出为:

UserList(列表(用户(Foo,列表(Foo@gmail.com,foo2@gmail.com)),用户(栏,列表(Bar@gmail.com,bar @ gmail.com))))