I am currently trying to extract the information from a json array using json4s (scala).
我目前正在尝试使用json4s (scala)从json数组中提取信息。
An example data is as follows:
示例数据如下:
val json = """
[
{"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
{"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}
]
"""
And my code is as follows:
我的代码如下:
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)
The output turns out to be:
输出结果为:
type: class UserList
users: List()
It seems that the data is not correctly retrieved. Is there any problem with my code?
似乎数据没有被正确地检索到。我的代码有问题吗?
UPDATE: It works according to the suggestion of @Kulu Limpa.
更新:根据@Kulu Limpa的建议工作。
1 个解决方案
#1
18
Your code is correct except that your JSON is simply an array, hence a List[User]
. There are two ways to fix this, with a slightly different outcome:
您的代码是正确的,除了您的JSON只是一个数组,因此是一个列表[用户]。有两种方法可以解决这个问题,但结果略有不同:
Solution 1: Fix your json to
解决方案1:将json修改为
{"users":
[
{"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
{"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}
]
}
Solution2: Change the type parameter of extract to
解决方案2:将提取的类型参数更改为
val obj = parse(json).extract[List[User]]
#1
18
Your code is correct except that your JSON is simply an array, hence a List[User]
. There are two ways to fix this, with a slightly different outcome:
您的代码是正确的,除了您的JSON只是一个数组,因此是一个列表[用户]。有两种方法可以解决这个问题,但结果略有不同:
Solution 1: Fix your json to
解决方案1:将json修改为
{"users":
[
{"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
{"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}
]
}
Solution2: Change the type parameter of extract to
解决方案2:将提取的类型参数更改为
val obj = parse(json).extract[List[User]]