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

Raj*_*esh 59 iphone json objective-c ios

我用过这种方法,

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

它打印"jsonObject为null".
"error:nil"有问题吗?
我没有使用任何网址或连接方法.
我有一个json文件,我想在表中显示它.

ami*_*oni 155

请尝试以下代码.

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

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

NSLog(@"loans: %@", latestLoans);
Run Code Online (Sandbox Code Playgroud)

  • 然后在浏览器中输入您的网址,然后您将获得字典或数组然后复制所有数据并将其粘贴到此链接http://jsonlint.com/如果您的json有效然后它将显示或是否有任何错误然后将显示空值. (4认同)

iAh*_*med 9

万一有人在这里看到快速代码:

NSData到NSDictionary

let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary
Run Code Online (Sandbox Code Playgroud)

NSData到NSString

let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)


小智 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];
}
Run Code Online (Sandbox Code Playgroud)

输出:

2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
    key1 = value1;
}
Run Code Online (Sandbox Code Playgroud)