60

这个方法我用过

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

它正在打印“jsonObject 为空”。
“错误:无”有什么问题吗?
我没有使用任何 url 或连接方法。
我有一个 json 文件,我想在表格中显示它。

4

5 回答 5

155

请尝试以下代码。

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

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

NSLog(@"loans: %@", latestLoans);
于 2012-09-26T14:26:25.437 回答
9

以防万一有人在这里查看快速代码:

NSData 到 NSDictionary

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

NSData 到 NSString

let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)
于 2015-10-27T06:28:46.923 回答
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;
}
于 2012-09-26T14:09:37.587 回答
0
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

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

于 2016-03-25T21:22:50.647 回答
-1

让convertedJsonIntoDict = 试试JSONSerialization.jsonObject(with: data!, options: []) as? NS词典

于 2018-04-05T08:58:12.037 回答