问题
I am getting some web response in the below format, The problem is testMap
is of dynamic type. Key of the object as well as the data type is dynamic. testMap will be a dictionary type object, which'll contain dynamic data in its dynamic key. As you can see, it can be string, array of string or array of integers.
{"results": [
{"tests": [{
"testsType": "A",
"testMap": {
"testId": "5a7c4fedec7fb72b7aa9b36e"}}]
},
{
"tests": [{
"testsType": "B",
"testMap": {
"myIds": ["2112"]}}]
}]
}
I tried to use this answer but It didn't work cause the value type is unknown in my case. testMap:[String:Any]
didn't work, cause Any
doesn't conform to Codable
.
Model
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
}
回答1:
This will decode your 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]?
}
And, obviously:
do {
let result = try JSONDecoder().decode(Results.self, from: data)
print(result)
} catch {
print(error)
}
来源:https://stackoverflow.com/questions/49181230/how-to-decode-a-nested-json-key-which-holds-dynamic-object-using-codable