JSON Parsing in Swift 3

前端 未结 8 847
暖寄归人
暖寄归人 2020-12-01 11:05

Has anyone been able to find a way to parse through JSON files in Swift 3? I have been able to get the data to return but I am unsuccessful when it comes to breaking the dat

8条回答
  •  生来不讨喜
    2020-12-01 11:25

    JSON Parsing in swift 4 using Decodable Protocol :

    I create a mocky file using your json object :

    http://www.mocky.io/v2/5a280c282f0000f92c0635e6

    Here is the code to parse the JSON :

    Model Creation :

    import UIKit
    
    struct Item : Decodable { 
    // Properties must be the same name as specified in JSON , else it will return nil
    var Number : String
    var Name : String
    }
    
    struct Language : Decodable {
     var Field : [Item]
    }
    
    struct Result : Decodable {
     var Language : Language
    }
    

    You can use optional in the model if you are uncertain that something might be missing in JSON file.

    This is the parsing Logic :

    class ViewController: UIViewController {
    
    let url = "http://www.mocky.io/v2/5a280c282f0000f92c0635e6"
    
    private func parseJSON() {
    
        guard let url = URL(string: url) else { return }
    
        let session = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }
            guard let result = try? JSONDecoder().decode(Result.self, from: data) else { return }
            print("\n\nResult : \(result)")
        }
        session.resume()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        parseJSON()
    }
    }
    

    The Print Output :

     Result : Result(Language: JSON_Parsing.Language(Field: [JSON_Parsing.Item(Number: "976", Name: "Test"), JSON_Parsing.Item(Number: "977", Name: "Test")]))
    

    This the github Project link. You can check.

提交回复
热议问题