Automatic JSON serialization and deserialization of objects in Swift

前端 未结 7 2060
走了就别回头了
走了就别回头了 2020-12-13 00:21

I\'m looking for a way to automatically serialize and deserialize class instances in Swift. Let\'s assume we have defined the following class …

class Person          


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 00:46

    There is a Foundation class called NSJSONSerialization which can do conversion to and from JSON.

    The method for converting from JSON to an object looks like this:

    let jsonObject = NSJSONSerialization.JSONObjectWithData(data, 
        options: NSJSONReadingOptions.MutableContainers, 
        error: &error) as NSDictionary
    

    Note that the first argument to this method is the JSON data, but not as a string object, instead as a NSData object (which is how you'll often times get JSON data anyway).

    You most likely will want a factory method for your class that takes JSON data as an argument, makes use of this method and returns an initialize object of your class.

    To inverse this process and create JSON data out of an object, you'll want to make use of dataWithJSONObject, in which you'll pass an object that can be converted into JSON and have an NSData? returned. Again, you'll probably want to create a helper method that requires no arguments as an instance method of your class.


    As far as I know, the easiest way to handle this is to create a way to map your objects properties into a dictionary and pass that dictionary for turning your object into JSON data. Then when turning your JSON data into the object, expect a dictionary to be returned and reverse the mapping process. There may be an easier way though.

提交回复
热议问题