我收到以下格式的网页回复,问题是testMap
属于动态类型。对象的键以及数据类型是动态的。 testMap将是一个字典类型对象,它将在其动态密钥中包含动态数据。如您所见,它可以是字符串,字符串数组或整数数组。
{"results": [
{"tests": [{
"testsType": "A",
"testMap": {
"testId": "5a7c4fedec7fb72b7aa9b36e"}}]
},
{
"tests": [{
"testsType": "B",
"testMap": {
"myIds": ["2112"]}}]
}]
}
我尝试use this answer但是它不起作用,因为我的情况下值类型未知。 testMap:[String:Any]
无效,因为Any
不符合Codable
。
模型
struct Results: Codable
{
let results: [Tests]
}
struct Tests: Codable
{
let tests: [Test]
}
struct Test: Codable
{
let testsType: String?
var testMap:[String:String] // Its wrong, cause value type is unknown
}
答案 0 :(得分:0)
这将解码您的JSON:
struct Results: Codable {
let results: [Tests]
}
struct Tests: Codable {
let tests: [Test]
}
struct Test: Codable {
let testsType: String
let testMap: TestMap
}
struct TestMap: Codable {
let testId: String?
let myIds: [String]?
}
显然:
do {
let result = try JSONDecoder().decode(Results.self, from: data)
print(result)
} catch {
print(error)
}