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

橙三吉。 提交于 2019-12-02 06:07:59

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!