Reputation: 1017
So, I've been reading a boatload of material on this topic for several days already. I've solved most of my problems except few. These are the following: 1)How do you serialize Dictionary of Custom classes to JSON,(considering that each class is serializable) 2) How to deserialize JSON, which is a contains Dictionary into actual Dictionary, provided that UserObject alone can be serialized.
For serialization I use this protocol: https://gist.github.com/anaimi/ad336b44d718430195f8#file-serializable-swift
For deserialization I just pull values from json. It works with all the primitives and custom types, but I don't know how to deserialize collections of custom types.
For example, here is my code for serialization:
@objc var jsonProperties:Array<String> {
get {
return ["id","login","password","name","picture","reputation","description","gender","x","y","visibility","friendRequests","friendWeightings","interestWeightings"]
}
}
@objc func valueForKey(key: String!) -> AnyObject! {
if key == "id" {
return self.id
} else if key == "login" {
return self.login
} else if key == "password" {
return self.password
} else if key == "name" {
return self.name
}
}
ANd so on...
That's how I deserialize the same object: init() {}
init(json: JSON) {
if let i = json["id"].string {
self.id = i
}
if let l = json["login"].string {
self.login = l
}
if let f: Array<String> = json["someArray"].arrayObject as? [String] {
self.friendRequests = f
}
if let f = json["someDictionary"].dictionaryObject as? Dictionary<String,Float> {
self.friendWeightings = f
}
}
The problem arises when I try to serialize or deserialize A COLLECTION(like an Array or Dictionary) of that class
Has somebody encountered that problem before?
In addition, I don't think that Serializable protocol serializes Dictionaries of NON-Primitive types correctly. I haven't looked into it yet.
Anyway, the point is: Is there a nice library, which does all the serialization/deserialization of ANY data I send OR if there is no such thing, what is the way to serialize/deserialize collections of custom types to json.
Thank You.
Upvotes: 0
Views: 842
Reputation: 1017
So I finally found a solution. I bridged JSONModel to my swift project. It does all the serialization correctly from and to JSON. The only thing, which was left is to add serialization and deserialization to classes. Nothing tricky, a lot of mechanical work of writing if let code. Dictionaries were tricky, first of all I checked if the dictionary exists if so, then I wrote down each key to my dictionary but for value I needed to transform JSONModel type to my type. Anyway, I seemed to achive everything that I wanted, although Apple should get it straight and write a high-quality level json library.
Upvotes: 1