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

后端 未结 1 1931
刺人心
刺人心 2021-01-24 15:33
{
  \"0\": {
    \"name\": \"legaldoc.pdf\",
    \"cmisid\": \"yib5C-w92PPtxTBlXl4UJ8oDBthDtAU9mKN5kh2_KrQ\"
  },
  \"1\": {
    \"name\": \"persdoc.pdf\",
    \"cmisi         


        
相关标签:
1条回答
  • 2021-01-24 15:58

    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)
    }
    
    0 讨论(0)
提交回复
热议问题