如何使用json4s从json数组中解析和提取信息

yxj*_*ang 9 json scala json4s

我目前正在尝试使用json4s(scala)从json数组中提取信息.

示例数据如下:

val json = """
  [
    {"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
    {"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}
  ]
"""
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

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

val obj = parse(json).extract[UserList]
printf("type: %s\n", obj.getClass)
printf("users: %s\n", obj.users.toString)
Run Code Online (Sandbox Code Playgroud)

输出结果是:

type: class UserList
users: List()
Run Code Online (Sandbox Code Playgroud)

似乎没有正确检索数据.我的代码有问题吗?

更新:根据@Kulu Limpa的建议工作.

Kul*_*mpa 18

你的代码是正确的,除了你的JSON只是一个数组,因此a List[User].有两种方法可以解决这个问题,结果略有不同:

解决方案1:修复你的json

{"users": 
  [
    {"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
    {"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}
  ]
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:将提取的类型参数更改为

val obj = parse(json).extract[List[User]]
Run Code Online (Sandbox Code Playgroud)