使用Swift 4将多级JSON解码为结构是零

时间:2018-05-15 09:45:21

标签: swift swift4 codable

这是对象数据服务器的反馈,我打算用swift4.0 JSONDecoder将它解码到我的struct,但是我遇到了一些问题,结果总是nil:

{
"code":"000000",
"isAutoRequest":0,
"message":"wwwwwww",
"ruleList":[
    {
        "rateList":[{
                "rate":"2.1",
                "rateCode":1,
                "rateName":1
            },{
                "rate":"2.1",
                "rateCode":2,
                "rateName":2
            },{
                "rate":"2.1",
                "rateCode":3,
                "rateName":3
            }],
        "ruleCode": "sanjundaxiao",
        "ruleName": "eeeeee",
        "sort": "07"
    },
    {
        "rateList":[{
                "rate": "185",
                "rateCode": 111,
                "rateName": 111
            },{
                "rate": "185",
                "rateCode": 222,
                "rateName": 222
            }],
        "ruleCode": "code2",
        "ruleName": "eeeqqqqq",
        "sort": "08"
    }]

}

这是解码服务器数据的结构:

struct GroupRateModel:Codable {
    var isAutoRequest:String?
    var ruleList:[RuleRateList]?
    var code:String?
    var message:String?
}

struct RuleRateList:Codable {
    var rateList:[RateList]?
    var ruleCode:String?
    var ruleName:String?
    var sort:String?
}

struct RateList:Codable {
    var rate:String?
    var rateCode:String?
    var rateName:String?
}

我使用以下代码解码数据,但结果(dataModel为nil)总是为零,我不知道哪里出错了,我是swift的新人,希望有人能告诉我正确的方法谢谢!

 let decoder = JSONDecoder()
 let resultData = try? JSONSerialization.data(withJSONObject: resultDic, options: [])
 if let data = resultData{
    let dataModel = try? decoder.decode(GroupRateModel.self, from: data)
}

0 个答案:

没有答案