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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27052477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:43:44  来源:igfitidea点击:

How to parse and extract information from json array using json4s

jsonscalajson4s

提问by yxjiang

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": ["[email protected]", "[email protected]"]},
    {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}
  ]
"""

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 的建议工作。

回答by Kulu Limpa

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 只是一个数组,因此List[User]. 有两种方法可以解决这个问题,但结果略有不同:

Solution 1: Fix your json to

解决方案 1:将您的 json 修复为

{"users": 
  [
    {"name": "Foo", "emails": ["[email protected]", "[email protected]"]},
    {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}
  ]
}

Solution2: Change the type parameter of extract to

解决方案2:将extract的类型参数改为

val obj = parse(json).extract[List[User]]