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

如何将json值转换为整数数组[Swift],swift,Swift,在我的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]

在我的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]”转换为整数数组?

您的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)