简体   繁体   中英

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

I got to know struct "Codable" in swift 4.0, *. So, I tried that when decode josn.

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

Example sample data model below.

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

And sample json data is .. below.

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

But i want filtering wrong data. If the value of "no" is less than or equal to 0, it is an invalid value.

Before not using codable...below. (using Alamifre ison response )

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

how to filter wrong data or invalid data using swift 4.0 Codable ??

Yes, you have to use filters for that with codable:

1: Your struct should be according to your response like that:

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: Parse your response using a codable struct like that:

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: now you can filter invalid data simply:

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

you can make codable for inital resonse

Here is your model :

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

And use it like that :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM