简体   繁体   中英

get position in a api swift Codable and Model data

i am getting data from an api like this

[
  {
    "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",
  }
]

I have my model like this

struct PersonData: Codable {
    let author: String?
    let description: String?
    let url: String?
}

But I dont know how to define the "internData", I tried with another Model "InterData" and define id and name like the PersonData, but i get an error, i tried also with [String:Any] but i get an error for the Codable protocol

I am using

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

in my script of Service/Network

Thanks if somebody knows

You can't use [String:Any] type in case of Codable . you need to create an another model of InternData , which is used by PersonData .

Code:

JSON Data :

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",
}
]
"""

// Models

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

// New model 

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

// Parsing

do {
    let parseRes = try JSONDecoder().decode([PersonData].self, from: Data(jsonData.utf8))
    print(parseRes)
}
catch {
     print(error)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM