NSJSONSerialization parsing response data

℡╲_俬逩灬. 提交于 2019-12-04 18:23:38

As Jeremy pointed out, you shouldn't escape the quotes in the JSON data. But also, you've quoted the return string. That makes it a JSON string, not an object, so when you decode it you've got a string, not a mutable array, which is why you get an error when you try to fast iterate... you're not able to fast iterate over a string.

Your actual JSON should look like: [{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}]. No quotes, no escapes. Once you eliminate the quotes around your JSON object, your app won't crash anymore, but then you're going to get a JSON deserialization error for malformed data (the escapes).

The likely cause is you are using the wrong foundation object. Try changing NSMutableArray to NSDictonary.

From:

NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];

To:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];

Parsing with NSJSONSerialization is easy, but I have also created a little framework that allows parsing JSON values directly into class objects, instead of dealing with dictionaries. Take a look, it might be helpful: https://github.com/mobiletoly/icjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!