如何过滤无效数据使用swift 4.1 codable(json decode)

时间:2018-05-20 09:25:50

标签: json swift decode codable decodable

我在swift 4.0中了解了struct“Codable”,*。 所以,我在解码josn时试过了。

if let jsonData = jsonString.data(using: .utf8) {
    let decodingData = try? JSONDecoder().decode(SampleModel.self, from: jsonData)
}

以下示例数据模型。

struct SampleModel : Codable {
    var no: Int?
    var category: Int?
    var template_seq: Int?
}

示例json数据在..下面。

{
    "data": {
        "result" : 1 
        "total_count": 523,
        "list": [
            {
                "no": 16398,
                "category" : 23,
                "template_seq" : 1
            },
            {
                "no": -1,
                "category" : 23,
                "template_seq" : 1
            }
        ]
    }
}

但我想过滤错误的数据。 如果“no”的值小于或等于0,则它是无效值。

在不使用可编码的......之前。 (使用Alamifre ison回复)

guard let dictionaryData = responseJSON as? [String : Any]  else { return nil }

guard let resultCode = dictionaryData["result"] as? Bool , resultCode == true  else { return nil }

guard let theContainedData = dictionaryData["data"] as? [String:Any] else { return nil }

guard let sampleListData = theContainedData["list"] as? [[String : Any]] else { return nil }

var myListData =  [MyEstimateListData]()

for theSample in sampleListData {
    guard let existNo = theSample["no"] as? Int, existNo > 0 else {
        continue
    }
    myListData.append( ... ) 
}

return myListData

如何使用swift 4.0 Codable过滤错误数据或无效数据?

2 个答案:

答案 0 :(得分:-1)

是的,您必须使用带有可编码的过滤器:

1:您的结构应该根据您的反应:

struct SampleModel : Codable {
    var result: Int?
    var total_count: Int?
    var list: [List]?
}
struct List : Codable {
    var no: Int?
    var category: Int?
    var template_seq: Int?
}

2:使用codable结构解析您的响应:

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryData["data"] as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
    let resultData = try JSONDecoder().decode(SampleModel.self, from: jsonData)
    success(result as AnyObject)
} catch let message {
    print("JSON serialization error:" + "\(message)")
}

3:现在您可以简单地过滤无效数据:

let filterListData = resultData.list?.filter({$0.no > 0})
let invalidData = resultData.list?.filter({$0.no <= 0})

答案 1 :(得分:-1)

你可以为初始共鸣做好准备

以下是您的模型

import Foundation

struct Initial: Codable {
    let data: DataModel?
}

struct DataModel: Codable {
    let result, totalCount: Int
    let list: [List]?

    enum CodingKeys: String, CodingKey {
        case result
        case totalCount = "total_count"
        case list
    }
}

struct List: Codable {
    let no, category, templateSeq: Int

    enum CodingKeys: String, CodingKey {
        case no, category
        case templateSeq = "template_seq"
    }
}

extension Initial {
    init(data: Data) throws {
        self = try JSONDecoder().decode(Initial.self, from: data)
    }
}

并使用它:

if let initail  = try? Initial.init(data: data) , let list = initail.data?.list {
               var myListData = list.filter { $0.no > 0 }
            }