我有一个从API获得的JSON响应,JSON如下所示
{
"data": [
{
"_id": "63d9d2d57c0cfe791b2b19f6",
"step": {
"_id": "step1",
"status": "STARTED",
"children": [
{
"_id": "step2",
"status": "NOT_STARTED",
"children": [
{
"_id": "step3",
"status": "NOT_STARTED",
"children": [
{
"_id": "step3",
"status": "NOT_STARTED"
}
]
}
]
}
]
},
"status": "IN_PROGRESS",
"createdBy": "2700930039"
}
]
}
JSON可以在彼此内部具有多层子对象.我需要将此JSON响应映射到SWIFT中的模型
以下是我为Json创建的模型
struct NestedJsonModel:Decodable {
var data:[LotData]
}
struct LotData:Decodable {
var _id: String
var step: StepDetails
var status: String
var createdBy: String
}
struct StepDetails:Decodable {
var _id: String
var status: String
var children: [ChildSteps]
}
struct ChildSteps:Decodable {
var _id: String
var status: String
var children: [StepDetails] //because children contains the same model as Step Details
}
以下是译码代码
let jsonData = data.data(using: .utf8)!
do {
let decoder = JSONDecoder()
let tableData = try decoder.decode(NestedJsonModel.self, from: jsonData)
result = tableData.data
print("****************")
print(result!)
print("****************")
}
catch {
print (error)
}
但我一直收到这样的错误
keyNotFound(CodingKeys(stringValue: "children", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "step", intValue: nil), CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"children\", intValue: nil) (\"children\").", underlyingError: nil))
个