如何将JSON序列化数据转换为NSDictionary

60

我已经使用了这种方法。

NSDictionary *jsonObject=[NSJSONSerialization 
       JSONObjectWithData:jsonData 
                  options:NSJSONReadingMutableLeaves 
                    error:nil];
NSLog(@"jsonObject is %@",jsonObject);

它打印出 "jsonObject is null"。 是否 "error:nil" 有问题? 我没有使用任何url或连接方法。 我有一个json文件,我想在表格中显示它。


你检查过jsonData不是nil了吗?如果想要获取一些错误描述,你可以传递一个NSError对象给调用函数。 - onnoweb
1
你可以在这里找到答案如何使用NSJSONSerialization - Ivan Dyachenko
@Ivan Dyachenko:我也做了同样的事情..... "NSError *myerror=nil; then "error:&myerror;" 但是即使这样,我仍然得到了null...... - Rajesh
这个应该叫做“JSON序列化数据到NSDictionary”,NSData到NSDictionary以及相反的转换答案可以在这里找到... https://dev59.com/VW035IYBdhLWcg3wSN8G - serge-k
5个回答

155
请尝试以下代码。
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

4
请将以下文本翻译成中文:然后在浏览器中输入您的网址,然后您将获得字典或数组,然后复制所有数据并粘贴到此链接http://jsonlint.com/中,如果您的JSON有效,则会显示,如果有任何错误,则会显示null。 - amit soni

9

如果有人想查看 Swift 代码的话:

NSData 转成 NSDictionary

let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary

将NSData转换为NSString

let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)

1
对于 Swift 4:
let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)! as! NSDictionary
- zaheer

6

检查您的JSON输入,可能是因为您的根元素既不是字典也不是数组?文档表示,在这种情况下,您需要指定NSJSONReadingAllowFragments作为选项。

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonObject=[NSJSONSerialization 
           JSONObjectWithData:jsonData 
                      options:NSJSONReadingMutableLeaves 
                        error:nil];
    NSLog(@"jsonObject is %@",jsonObject);

    [p release];
}

输出:

2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
    key1 = value1;
}

0
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

这只是顶部帖子的更简洁版本。


-1
让convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接