I try to convert a JSON response from the server to an object. I use Swift.
This is the result of printing the server response:
(
{
1 = Horst;
2 = Schnitzelhuber;
3 = "0161 2213310";
id = 0000040001;
status = 2;
},
{
1 = "Mar\U00f0a";
3 = "0163 5419374";
id = 0000040005;
status = 2;
}
)
This is my model:
class Profil: JSONSerializable {
var id: String?
required init() {}
class func map(source: JsonSZ, object: Profil) {
object.id <= source["id"]
}
}
I have been using SwiftJZ for parsing so far.
let test: [Profil!]? = serializer.fromJSONArray(response, to: Profil.self)
If I try to print the mapped object:
println(test?[0].id)
=> result is always nil
This is the relevant method from JSONSZ:
public func fromJSONArray<N: JSONSerializable>(JSON: AnyObject, to type: N.Type) -> [N]? {
if let string = JSON as? String {
if let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
=> FAIL if let array = parsed as? [[String: AnyObject]] {
var objects: [N] = []
for element in array {
self.values = element
var object = N()
N.map(self, object: object)
objects.append(object)
}
return objects
}
}
}
return nil
}
Could you help me to solve this issue fast?
Perhaps another library...
Finally I want to save this objects of the model into Cora Data.
EDIT:
public func fromJSONArray<N: JSONSerializable>(JSON: AnyObject, to type: N.Type) -> [N]? {
if let string = JSON as? String {
if let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
Here is the problem: let parsed is nil. That's why the serialization fails.