I am new to Swift, and have been trying to parse JSON from an API call. I have the parse part down, and I have made structs that relate to the JSON data :
struct Result: Codable {
let data: [PeopleData]
}
struct PeopleData: Codable {
let name: String
let address: String
let friends: [String]
However, I am not sure if this is the correct format. Here is the JSON :
{
"data": [
{
"name": "Mike",
"address": "72 Highway Boulevard",
"friends": [
{
"name": "Joe",
"address": "1234 Rainbow Road"
},
{
"name": "Andy",
"address": "885 Street Road
}
]
}
]
}
I cannot change the JSON format, so how would I create structs that adhere to the format of JSON? I understand that [] is an array, and {} is an object in JSON, so I am just trying to sort this out. Thanks in advance
CodePudding user response:
friends
is not a String array, it should also be a Struct:
struct Result: Codable {
let data: [PeopleData]
}
struct FriendData: Codable {
let name: String
let address: String
}
struct PeopleData: Codable {
let name: String
let address: String
let friends: [FriendData]
}
should work.
Nitpick: If you do not need to encode those back, Decodable
should be enough instead of Codable
.
P.S: QuickType is also a great tool for this.