Simple and clean way to convert JSON string to Object in Swift

前端 未结 16 1246
挽巷
挽巷 2020-11-28 23:27

I have been searching for days to convert a fairly simple JSON string to an object type in Swift but with no avail.

Here is the code for web service call:



        
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 00:00

    I wrote a library which makes working with json data and deserialization a breeze in Swift. You can get it here: https://github.com/isair/JSONHelper

    Edit: I updated my library, you can now do it with just this:

    class Business: Deserializable {
        var id: Int?
        var name = "N/A"  // This one has a default value.
    
        required init(data: [String: AnyObject]) {
            id <-- data["id"]
            name <-- data["name"]
        }
    }
    
    var businesses: [Business]()
    
    Alamofire.request(.GET, "http://MyWebService/").responseString { (request, response, string, error) in
        businesses <-- string
    }
    

    Old Answer:

    First, instead of using .responseString, use .response to get a response object. Then change your code to:

    func getAllBusinesses() {
    
        Alamofire.request(.GET, "http://MyWebService/").response { (request, response, data, error) in
            var businesses: [Business]?
    
            businesses <-- data
    
            if businesses == nil {
                // Data was not structured as expected and deserialization failed, do something.
            } else {
                // Do something with your businesses array. 
            }
        }
    }
    

    And you need to make a Business class like this:

    class Business: Deserializable {
        var id: Int?
        var name = "N/A"  // This one has a default value.
    
        required init(data: [String: AnyObject]) {
            id <-- data["id"]
            name <-- data["name"]
        }
    }
    

    You can find the full documentation on my GitHub repo. Have fun!

提交回复
热议问题