-
Notifications
You must be signed in to change notification settings - Fork 142
Working with Arrays at the Root #106
Comments
it's not clear to me that there's a good way to handle that situation the library itself. it could be managed client-side by doing the following. create a model with a new initializer that takes in JSON array - and creates a JSON dictionary with a custom key, which is passed to the required initializer: struct Test: Glossy {
let urls: [String]
// introduce JSON array initializer that creates JSON with a custom key
init?(jsonArray: [AnyObject]) {
let jsonDictionary = ["myCustomJSONArrayKey" : jsonArray]
self.init(json: jsonDictionary)
}
init?(json: JSON) {
guard let urls: [String] = "myCustomJSONArrayKey" <~~ json else {
return nil
}
self.urls = urls
}
func toJSON() -> JSON? {
return jsonify([
"myCustomJSONArrayKey" ~~> self.urls
])
}
} client-side, use the custom key to retrieve values: let testJSON = [ "http://google.com", "http://facebook.com" ]
let test = Test(jsonArray: testJSON)
print(test?.urls)
// use the custom key to retrieve array
let myJSON: [String]? = test?.toJSON()?["myCustomJSONArrayKey"] as? [String]
print(myJSON) i get its not ideal - but the designation of JSON as a dictionary is currently part of the library. thoughts on this solution? |
The solution works but I guess this will increase more work for the developer. Refer to https://github.com/thoughtbot/Argo/blob/master/Argo/Types/JSON.swift. It is handling all the scenarios of JSON. The same issue exists with Alamofire also. The parameters are the type of [String: AnyObject] so it doesn't allow us to send post requests using Array of objects. We always have to keep a rootKey like "results" and then pass the array into it. I can work on this with the test cases if you like. I kind of need this functionality to save myself from extra work 😋. |
sure, if you have the time to work on it. i'd love to see what you come up with |
Update: I was able to solve this in Reactofire itself and it seems to work without changing the Gloss Library. Regards |
Suppose i have array of URLS. I am trying to convert the below to NSURL objects but couldn't find any method.
But if i have a rootKey like the below json. I can use Decoder.decodeURLArray("urls")(json).
I guess JSON should be AnyObject instead of [String: AnyObject].
The text was updated successfully, but these errors were encountered: