Scala 解析嵌套 json 与 Json4s

Scala parsing nested json with Json4s

我正在尝试从嵌套 JSON 中获取数据,我只需要 JSON 中的几个字段, 我已经为所需数据创建了案例 类,我从 google 中找到的解决方案建议使用 read 函数,但我得到一个空对象 我尝试 google 但没有成功,我错过了什么? 我的代码

val rawDataFromFile = Source.fromFile(path).mkString

case class Data(listOfPersons: List[Person])

case class Person(bio: Bio, terms: List[Term])

case class Bio(birthday: String, gender: String)

case class Term(`type`: String, start: String, end: String)

read[Data](rawDataFromFile)

res >> Data(List())

和JSON

[
  {
    "id": {
      "not_intresting_field_1": "B000944",
      "not_intresting_field_4": [
        "H2OH13033",
        "S6OH00163"
      ]
    },
    "name": {
      "first": "first_name_1",
      "last": "last_name_1"
    },
    "bio": {
      "birthday": "1952-11-09",
      "gender": "M"
    },
    "terms": [
      {
        "type": "rep",
        "start": "1993-01-05",
        "end": "1995-01-03"
      },
      {
        "type": "rep",
        "start": "1995-01-04",
        "end": "1997-01-03"
      }
    ]
  },
  {
    "id": {
      "not_intresting_field_1": "C000127",
      "not_intresting_field_4": [
        "S8WA00194",
        "H2WA01054"
      ]
    },
    "name": {
      "first": "first_name_1",
      "last": "last_name_1"
    },
    "bio": {
      "birthday": "1958-10-13",
      "gender": "F"
    },
    "terms": [
      {
        "type": "rep",
        "start": "1993-01-05",
        "end": "1995-01-03"
      },
      {
        "type": "sen",
        "start": "2001-01-03",
        "end": "2007-01-03"
      }
    ]
  }
]

您的案例 class 与您的 json 结构不同。

在此处定义 Data 类型,其内容如下 json

{
  "listOfPersons": [
  {
    "id": {
      "not_intresting_field_1": "B000944",
      "not_intresting_field_4": [
        "H2OH13033",
        "S6OH00163"
      ]
    },
    "name": {
      "first": "first_name_1",
      "last": "last_name_1"
    },
    "bio": {
      "birthday": "1952-11-09",
      "gender": "M"
    },
    ... //your original json
  }

  ]
}

试试这个

read[List[Person]](rawDataFromFile)