如何将json值转换为int数组[Swift]

时间:2018-08-06 01:48:15

标签: swift

在我的快捷应用程序中,我使用以下代码获取此JSON:[“ jsonArray”:“ [15,16]”]:

guard let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:String] else { return }

我的问题是:如何将json [“ jsonArray”](即“ [15,16]”)转换为整数数组?

1 个答案:

答案 0 :(得分:1)

您的JSON无效。我假设您的意思是{"jsonArray": "[15,16]"}(在外层使用花括号)。

最重要的是,它被可怕地编码。如果有机会,请另一端的开发人员进行更改。如果无法,则可以先将其解码为字符串,然后再次解码以获取整数:

struct Response: Decodable {
    private struct RawResponse: Decodable {
        let jsonArray: String
    }

    var numbers: [Int]
    init(from decoder: Decoder) throws {
        // First decode the array as a string
        let rawResponse = try RawResponse(from: decoder)

        // Then turn it into a Data struct
        let jsonData = rawResponse.jsonArray.data(using: .utf8)!

        // And finally decode it as an Int array
        self.numbers = try JSONDecoder().decode([Int].self, from: jsonData)
    }
}

let response = try JSONDecoder().decode(Response.self, from: json)
print(response)