![](/img/trans.png)
[英]How to parse this type of json format in swift 4 with decodable?
[英]how to use swift decodable protocol to parse nested JSON data?
我有一個從服務器獲取一些JSON數據的應用程序,看起來像這樣:
"operationsInfo": {
"bill": {
"activeProviders": [
{
"max": 50,
"min": 10,
"name": "name1"
},
{
"max": 50,
"min": 10,
"name": "name2"
}
]
},
"pin": {
"activeProviders": [
{
"max": 50,
"min": 10,
"name": "name3"
},
{
"max": 50,
"min": 10,
"name": name4
}
]
}
}
如何使用快速可解碼協議對該JSON數據進行反序列化? 我的自定義對象如下所示:
struct operationList: Decodable {
let name: String
let action: String
let min, max: Int
}
operationList對象中的操作值必須等於“ bill”或“ pin”。 最后,我想在解碼JSON數據時獲得一個operationList對象類型的數組,例如:
讓operationListArray = [operationList1,operationList2,operationList3,operationList4] operationList1.action =“ bill”,operationList1.max = 50,operationList1.name =“ name1” operationList2.action =“ bill”,operationList2.max = 50,operationList2.name =“ name2” operationList3.action =“ pin”,operationList3.max = 50,operationList3.name =“ name3” operationList4.action =“ pin”,operationList4.max = 50,operationList4.name =“ name4”
我已經看到其他類似的答案,例如: 如何使用Swift Decodable協議解碼嵌套的JSON結構? 但是我的問題是如何將“ bill”或“ pin”放在操作值中,並且將來可能將新的鍵值(例如“ transfer”(例如“ pin”或“ bill”)添加到JSON數據中)。
正如@rmaddy在評論中提到的那樣,您要分兩個步驟進行操作。
首先,創建一個與您的JSON格式匹配的結構並將其解碼:
struct Response: Decodable {
let operationsInfo: [String: Providers]
}
struct Providers: Decodable {
let activeProviders: [Provider]
}
struct Provider: Decodable {
let name: String
let min: Int
let max: Int
}
let response = try JSONDecoder().decode(Response.self, from: data)
然后,聲明一個結構,該結構表示您希望數據使用的格式並進行映射:
struct ProviderAction {
let action: String
let provider: Provider
}
let actions: [ProviderAction] = response.operationsInfo.map { action, providers in
providers.activeProviders.map { ProviderAction(action: action, provider: $0) }
}.flatMap { $0 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.