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

天大地大妈咪最大 提交于 2019-12-20 05:44:21

问题


{
  "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)
}


来源:https://stackoverflow.com/questions/48124453/swift-4-codable-the-keys-are-int-array-in-json-data

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