Swift: Decodable

Godfather

New Member
#1
Lets say i have this json from an API request:
Mã:
friends: { 
   "john":31,
   "mark":27,
   "lisa":17,
   "tom":41
}
I usually expect it in an array format:
Mã:
friends: [ 
   { "john":31 },
   { "mark":27 },
   { "lisa":17 },
   { "tom":41 }
]
But the API doesn't provide me this way the results. So i want finally to map it to an array of [Friend], where Friend is:
Mã:
class Friend: Decodable {
  let name: String
  let age: Int
}
How should i serialize this json to get [Friend] ?
 

Admin

Administrator
Thành viên BQT
#2
First of all, example isn't valid json at all. To be valid it either shouldn't include "friends" label, or it should be embedded in another object like this
Mã:
{
  "friends": { 
    "john":31,
    "mark":27,
    "lisa":17,
    "tom":41
  }
}
If I understand question correctly, you want to decode json object to swift array. I don't think there is a way to do so without writing custom decoding. Instead, you can decode json into Dictionary and when manually map it like so
Mã:
struct Friend {
    let name: String
    let age: Int
}

struct Friends: Decodable {
    let friends: [String: Int]
}

let friends = try! JSONDecoder().decode(Friends.self, from: json.data(using: .utf8)!)
    .friends
    .map { (name, age) in Friend(name: name, age: age) }
 
Top