How to deserialize JSON for object in Swift WITHOUT mapping

Is there a way to deserialize a JSON response to a custom object in Swift

without having an individual map of each item.

I am currently doing this manually with SwiftyJSON

, but I still need to reserve each field:

var myproperty1 = json["myproperty1"].stringValue

      

However, based on the background C#

, this is as easy as one line of code:

JsonConvert.DeserializeObject<CustomObject>(jsonString); //No mapping needed.

      

Source - http://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Since I write a lot of API endpoints, I would like to avoid all template rendering code that can be error prone. Be aware that my JSON responses will be multiple levels with arrays of arrays. Therefore, any function must be recursive.

Co-local question: Automatic JSON serialization and object deserialization in Swift

+3


source to share


2 answers


You can use EVReflection . You can use code like:

var user:User = User(json:jsonString)

      

or



var jsonString:String = user.toJsonString()

      

See the GitHub page for a more detailed code example

+3


source


You need to use key encoding for this. You have to make your object a subclass of NSObject for KVC in order to work, and then you can loop through the JSON data items and use setValue: forKey to assign a value for each key in the dictionary.



Note that this would be dangerous: if the target did not contain a value for a specific key, your code will fail, so your program will split into JSON data containing invalid keys. Not good.

+1


source







All Articles