arrays - 如何使用路径中文件中的数组序列化 JSON 数组?

标签 arrays json swift nsjsonserialization jsonserializer

我使用 Swift 在我的 Xcode 项目中有一个 .json 文件。 我需要加载内容并解析以在我的 Controller 中使用,但是当我尝试将文件内容序列化为 jsonObject 时,我遇到了解析错误...

我已经阅读了另一个类似的问题,但我还没有找到一个类似的 JSON 数组来读取包含不同的结构和另一个 JSON 数组到对象中。

数组JSON格式为:

[
  {
    "title": "The App",
    "description": "This is the description",
    "friends": [
      {
        "name": "Gary",
        "image": "http://",
        "description": "Nice"
      },
      {
        "name": "Patri",
        "image": "http://",
        "description": "Amazing"
      },
      {
        "name": "Lucy",
        "image": "http://",
        "description": "Up"
      }
    ]
  }
]

我正在使用这段代码从包路径(data.json 添加到我的项目)中获取文件的内容,然后序列化,但总是会出错,因为 Friends 包含一个 json 数组。

let path = Bundle.main.path(forResource: "data", ofType: "json")
let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path!))
let jsonResult = try! JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String:Any]] //Here is the error parsing the array of Friend of JSON

我如何解析这个包含另一个 jsonObject 数组的 json 数组?

最佳答案

你需要使用Codable

// MARK: - Element
struct Root: Codable {
    let title, purpleDescription: String
    let friends: [Friend]

    enum CodingKeys: String, CodingKey {
        case title
        case purpleDescription = "description"
        case friends
    }
}

// MARK: - Friend
struct Friend: Codable {
    let name, image, friendDescription: String

    enum CodingKeys: String, CodingKey {
        case name, image
        case friendDescription = "description"
    }
}

let url = Bundle.main.url(forResource: "data", withExtension: "json")
let jsonData = try! Data(contentsOf:url)
let res = try! JSONDecoder().decode([Root].self,from:data)
print(res)

关于arrays - 如何使用路径中文件中的数组序列化 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57717300/

相关文章:

javascript - JS 中循环包含对象数组的对象

java - 帕斯卡三角形二维数组 - 格式化打印输出

c - 无法通过函数打印矩阵元素

Java - 将数组值传递给第二个数组

jquery - 如何在 jQuery 中使用 json 数据填充下拉列表?

javascript - 按 Enter 键时加载路径 JSON

json - 如何获取 ("fields")在 VBA-JSON 中工作

swift - 后台 URLSession + Combine?

swift - 如何快速加载本地主机

swift - Firebase iOS 从推送通知接收数据