3

Is there a way to deserialize a JSON response to a custom object in Swift WITHOUT having to individually map each element.

Currently I am doing it manually with SwiftyJSON but it still requires me to map every field redundantly:

var myproperty1 = json["myproperty1"].stringValue

However coming from a C# background it is as simple as one line of code:

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

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

Since I am writing many API endpoints I would like to avoid all the boilerplate mapping code that can be prone to errors. Keep in mind that my JSON responses will be multiple levels deep with arrays of arrays. So any function would need to be recursive.

Similiar question : Automatic JSON serialization and deserialization of objects in Swift

Community
  • 1
  • 1
Andrew M.
  • 382
  • 3
  • 11

2 Answers2

3

You could use EVReflection for that. You can use code like:

var user:User = User(json:jsonString)

or

var jsonString:String = user.toJsonString()

See the GitHub page for more detailed sample code

Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58
  • Nice library. You just added support for JSON today, awesome. I will test it out today and accept your answer if it works as intended. Will it gracefully handle errors as Duncan C pointed out? – Andrew M. Jun 16 '15 at 18:03
  • Thanks! if your json has a key that's not a property name, then that value will be ignored. – Edwin Vermeer Jun 16 '15 at 18:17
  • Doesn't seem to be working for nested JSON arrays. In your testJsonObject function try userOriginal.friends. – Andrew M. Jun 16 '15 at 20:37
  • What do you mean? in the testJsonObject function userOriginal does have a friends array containing the 2 users. Those users are also in the json when you do a .toJsonString() Also the Company nested object is populated correctly. It would be great if you could give me some lines of code that fail. Maybe even a unit test? Could you create an issue for this at https://github.com/evermeer/EVReflection/issues ? Thanks. – Edwin Vermeer Jun 17 '15 at 06:05
1

You should be able to use key value coding for this. You'd have to make your object a subclass of NSObject for KVC to work, and then you could loop through the elements of the JSON data and use setValue:forKey to assign a value for each key in the dictionary.

Note that this would be dangerous: If the target object did not contain a value for a specific key then your code would crash, so your program would crash on JSON data that contained invalid keys. Not a good thing.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I thought about doing that with something like http://stackoverflow.com/a/25252278/1594491 However I'm not sure how to make that recursive when I have objects that map to arrays within other arrays. There is no way to do error handling that would prevent an application crash? – Andrew M. Jun 15 '15 at 23:03