我目前正在尝试使用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的建议工作.
我试图从json数据集中提取值,其中每个记录具有n> 22个键值对.为了做到这一点,我实现了一个带有n个成员变量的case类.但是,scala 2.10.x编译器报告了"实现限制:案例类不能超过22个参数".
似乎问题来自scala编译器的限制,但有没有绕道来解决这个问题?
更新:
我试图将大案例类分解为较小的类(使用嵌套的案例类),但在这种情况下程序无法正确解析json.我认为json4s的实现不允许我们这样做.