簡體   English   中英

如何使用Swift 4.1 Codable過濾無效數據(JSON解碼)

[英]How to filter invalid data Using swift 4.1 codable ( json decode)

我很快就知道結構4.0中的“ 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篩選錯誤數據或無效數據?

是的,您必須為此使用帶有codable的過濾器:

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})

你可以使首字母共鳴

這是您的模型

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 }
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM