Reputation: 327
Here is a snippet of my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
do {
guard let json = try NSJSONSerialization.JSONObjectWithData
(data!, options: .MutableContainers) as? [NSDictionary] else {
throw HttpError.ParsingFailed
}
completionHandler(success: true, data:json, error: nil)
}
catch HttpError.ParsingFailed {
...
It works fine, if the response data has more than one element. However the NSJSONSerialization.JSONObjectWithData fails (goes in the else block which throws the exception), if there is only one item in the response. Why doesn't it still parse the response in this case, and returns an array with one element inside? How should be this problem generally solved?
Of course it would help to do an other parsing in the catch block with as? NSDictionary instead of as? [NSDictionary], but I would avoid this when possible.
EDIT: object to be parsed which works:
[
{
"id": 1,
"idConsumer": 12
},
{
"id": 2,
"idConsumer": 12
}
]
and which does not work:
{
"id": 65,
"delivery": {
"id": 29,
"idConsumer": 19
},
"postman": {
"id": 13,
"email": "testpostman"
},
"price": 89
}
Upvotes: 0
Views: 166
Reputation: 19922
It's failing because you are casting your JSON to [NSDictionary]
. When you get multiple objects, you get an array of dictionaries, but when you get a single object, you get a single dictionary.
You should try to cast to NSDictionary
if casting to [NSDictionary]
fails.
If both fail then you should throw the error.
Upvotes: 1