简体   繁体   English

如何使用Swift 4.1 Codable过滤无效数据(JSON解码)

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

I got to know struct "Codable" in swift 4.0, *. 我很快就知道结构4.0中的“ Codable” *。 So, I tried that when decode josn. 所以,我在解码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. 样本json数据在下面。

{
    "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. 如果“ no”的值小于或等于0,则它是无效值。

Before not using codable...below. 在不使用编码之前...如下。 (using Alamifre ison response ) (使用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

how to filter wrong data or invalid data using swift 4.0 Codable ?? 如何使用Swift 4.0 Codable筛选错误数据或无效数据?

Yes, you have to use filters for that with codable: 是的,您必须为此使用带有codable的过滤器:

1: Your struct should be according to your response like that: 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: Parse your response using a codable struct like that: 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: now you can filter invalid data simply: 3:现在您可以简单地过滤无效数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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