Swift 4 codable: the keys are Int array in JSON da

2019-03-02 13:42发布

问题:

{
  "0": {
    "name": "legaldoc.pdf",
    "cmisid": "yib5C-w92PPtxTBlXl4UJ8oDBthDtAU9mKN5kh2_KrQ"
  },
  "1": {
    "name": "persdoc.pdf",
    "cmisid": "dqAnrdNMXGTz1RbOMI37OY6tH9xMdxiTnz6wEl2m-VE"
  },
  "2": {
    "name": "certdoc.pdf",
    "cmisid": "6d7DuhldQlnb0JSjXlZb9mMOjxV3E_ID-ynJ0QRPMOA"
  }
}

How do I use Swift 4 Codable to parse JSON data like that? the problem is that the keys are Int array. How do I set CodingKeys for this?

回答1:

As mentioned in the comments there is no array. All collection types are dictionaries.

You can decode it as Swift dictionary. To get an array map the result to the values of the sorted keys

let jsonString = """
{
    "0": {
        "name": "legaldoc.pdf",
        "cmisid": "yib5C-w92PPtxTBlXl4UJ8oDBthDtAU9mKN5kh2_KrQ"
    },
    "1": {
        "name": "persdoc.pdf",
        "cmisid": "dqAnrdNMXGTz1RbOMI37OY6tH9xMdxiTnz6wEl2m-VE"
    },
    "2": {
        "name": "certdoc.pdf",
        "cmisid": "6d7DuhldQlnb0JSjXlZb9mMOjxV3E_ID-ynJ0QRPMOA"
    }
}
"""

struct Item : Codable {
    let name, cmisid : String
}

do {
    let data = Data(jsonString.utf8)
    let result = try JSONDecoder().decode([String: Item].self, from: data)
    let keys = result.keys.sorted()
    let array = keys.map{ result[$0]! }
    print(array)

} catch {
    print(error)
}