在api swed可编码和模型数据中获取位置

问题描述 投票:1回答:1

我正在从这样的api获取数据

[
  {
    "internData": {
      "id": "abc123",
      "name": "Doctor"
    },
    "author": "Will smith",
    "description": "Is an actor",
    "url": "https://www",
  },
  {
    "internData": {
      "id": "qwe900",
      "name": "Constructor"
    },
    "author": "Edd Bett",
    "description": "Is an Constructor",
    "url": "https://www3",
  }
]

我有这样的模特

struc PersonData: Codable {
    author: String?
    description: String?
    url: String?
}

但是我不知道如何定义“ internData”,我尝试使用另一个Model“ InterData”并定义id和名称,如PersonData,但是我遇到了错误,我也尝试了[String:Any]但我得到了编码协议错误

我正在使用

let resP = try JSONSerialization.jsonObject(with: data, options: .init()) as? [String: AnyObject]
            print("resP", )

使用我的服务/网络脚本

感谢有人知道

swift
1个回答
0
投票

[String:Any]的情况下,您不能使用Codable类型。您需要创建InternData使用的另一个模型,PersonData使用该模型。

代码:

JSON数据:

let jsonData =
"""
[
{
"internData": {
"id": "abc123",
"name": "Doctor"
},
"author": "Will smith",
"description": "Is an actor",
"url": "https://www",
},
{
"internData": {
"id": "qwe900",
"name": "Constructor"
},
"author": "Edd Bett",
"description": "Is an Constructor",
"url": "https://www3",
}
]
"""

//型号

struct PersonData: Codable {
    let author: String
    let description: String
    let url: String
    let internData : InternData
}

//新型号

struct InternData : Codable {
    let id : String
    let name : String
}

//解析

do {
    let parseRes = try JSONDecoder().decode([PersonData].self, from: Data(jsonData.utf8))
    print(parseRes)
}
catch {
     print(error.localizedDescription)
}
© www.soinside.com 2019 - 2024. All rights reserved.