如何反序列化json对象并分配给iOS中的NSDictionary

时间:2012-08-30 10:52:38

标签: ios json nsdictionary deserialization nsdata

这是我处理服务器响应的代码。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
 NSLog(@"connectionDidFinishLoading : %@", [[NSString alloc] initWithData:self.data    encoding:NSUTF8StringEncoding]);
 }

这是消息服务器对我的响应,NSLog JSON显示在控制台中。

connectionDidFinishLoading : {"ErrorCode":"CssParameterException","ErrorMessage":"An error has occurred, please try again later.","Success":false}

我的问题是:如何反序列化JSON并将其存储到本地变量NSDictionary *jsonData

有什么建议吗?请给我一些代码示例,谢谢!

1 个答案:

答案 0 :(得分:19)

NSError *e = nil
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];

如果您有NSString响应

NSError *e = nil
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];