首页 > 解决方案 > Codable: decoding by key

问题描述

Suppose I have an API that returns this json:

{
   "dogs": [{"name": "Bella"}, {"name": "Lucy"}], 
   "cats": [{"name": "Oscar"}, {"name": "Coco"}]
}

And a model that looks like this:

import Foundation

public struct Animal: Codable {
    let name: String?
}

Now I want to decode the array of Animal from the "dogs" key:

let animals = try JSONDecoder().decode([Animal].self, from: response.data!)

However, I somehow have to reference the "dogs" key. How do I do this?

标签: swiftcodable

解决方案


First of all, the JSON you provided is not valid JSON. So let's assume that what you actually mean is this:

{
    "dogs": [{"name": "Bella"}, {"name": "Lucy"}],
    "cats": [{"name": "Oscar"}, {"name": "Coco"}]
}

Then the problem with your code is merely this line:

let animals = try JSONDecoder().decode([Animal].self, from: response.data!)

You're claiming that the JSON represents an array of Animal. But it doesn't. It represents a dictionary with keys dogs and cats. So you just say so.

struct Animal: Codable {
    let name: String
}
struct Animals: Codable {
    let dogs: [Animal]
    let cats: [Animal]
}

Now everything will just work:

let animals = try JSONDecoder().decode(Animals.self, from: response.data!)

推荐阅读