如何使用NSJSONSerialization

160

我有一个JSON字符串(来自PHP的json_encode()),看起来像这样:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

我想将此内容解析为我的iPhone应用程序的某种数据结构。 我想最好的方式是有一个字典数组,所以数组中的第0个元素是具有键"id" => "1""name" => "Aaa"的字典。

不过我不太理解 NSJSONSerialization 如何存储这些数据。这是目前我的代码:

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

这只是我在另一个网站上看到的示例。我一直在尝试通过打印元素数量等方式来读取JSON对象,但总是得到EXC_BAD_ACCESS

我该如何使用NSJSONSerialization解析上述JSON,并将其转换为我提到的数据结构?


你的 data 变量可能为 nil。 - d.lebedev
这不是,我已经测试过了。 - Logan Serman
你尝试过查看错误对象中是否有相关信息吗? - Monolo
12个回答

220

您的根JSON对象不是字典,而是一个数组:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

这可能会让你清楚地了解如何处理它:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);
   }
}

1
@xs2bush 不需要,因为你没有创建 jsonArray,所以它应该是自动释放的。 - rckoenes
@Logan:是的,[JSON count]应该返回一个值。请看下面关于僵尸进程的答案。EXC_BAD_ACCESS几乎总是与僵尸进程有关。 - Olie
在这种情况下,item是给定JSON键值对中的键。您的for循环完美地工作,输出了我的每个JSON键。然而,我已经知道我想要的值的键,即'key'。我尝试获取此键的值并将其输出到日志,但失败了。还有什么进一步的见解吗? - Thomas Clowes
@ThomasClowes,您应该提出自己的问题,而不是在回答的评论中提问。 - rckoenes
@rckoenes - 这是同一个问题。为了避免创建重复的问题,我在这里继续讨论。 - Thomas Clowes
显示剩余3条评论

76

这是我用来检查接收到的 JSON 是否为数组或字典的代码:

NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];

if ([jsonObject isKindOfClass:[NSArray class]]) {
    NSLog(@"its an array!");
    NSArray *jsonArray = (NSArray *)jsonObject;
    NSLog(@"jsonArray - %@",jsonArray);
}
else {
    NSLog(@"its probably a dictionary");
    NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
    NSLog(@"jsonDictionary - %@",jsonDictionary);
}

我已经尝试了options:kNilOptions和NSJSONReadingMutableContainers,对于两者都可以正常工作。

显然,实际的代码不能像这样,在if-else块中创建NSArray或NSDictionary指针。


30

对我来说有效。 你的data对象可能为nil,并且正如rckoenes所指出的那样,根对象应该是一个(可变的)数组。请参考此代码:

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@", json);

(我不得不在JSON字符串中使用反斜杠转义引号。)


9

您的代码看起来很好,除了结果是一个NSArray而不是NSDictionary,这里有一个例子:

前两行只是使用JSON创建数据对象,与从网络中读取数据一样。

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *e;
NSMutableArray *jsonList = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"jsonList: %@", jsonList);

NSLog内容(字典列表):

jsonList: (
           {
               id = 1;
               name = Aaa;
           },
           {
               id = 2;
               name = Bbb;
           }
           )

这个选项(NSJSONReadingMutableContainers)是什么意思?我使用kNilOption一切正常。告诉我使用这些选项的目的。 - Zar E Ahmer
Google 搜索排名第一的内容:NSJSONReadingMutableLeaves:“指定 JSON 对象图中的叶字符串将被创建为 NSMutableString 实例。” - zaph
那MutableContainer怎么样? - Zar E Ahmer
抱歉,再次从谷歌搜索结果中获取:NSJSONReadingMutableContainers: “指定数组和字典被创建为可变对象。” - zaph
在Xcode中,还可以使用Option键点击NSJSONReadingMutableContainers,双击Option键则可查看完整文档。 - zaph
1
这些只有在您计划修改返回的 JSON 对象并保存回去时才有帮助。无论哪种情况,这些对象可能是自动释放的对象,这似乎是根本原因。 - Deepak G M

6
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

在上面的JSON数据中,您展示了一个包含多个字典的数组。要解析它,请使用以下代码:
NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
        for(int i=0;i<[JSONarray count];i++)
        {
            NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
             NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
        }

针对Swift 3/3+版本

   //Pass The response data & get the Array
    let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
    print(jsonData)
    // considering we are going to get array of dictionary from url

    for  item  in jsonData {
        let dictInfo = item as! [String:AnyObject]
        print(dictInfo["id"])
        print(dictInfo["name"])
    }

3
以下代码从Web服务器获取JSON对象,并将其解析为NSDictionary。在此示例中,我使用了返回简单JSON响应的openweathermap API。为了保持简单,此代码使用同步请求。
以下代码从Web服务器获取JSON对象,并将其解析为NSDictionary。在此示例中,我使用了返回简单JSON响应的openweathermap API。为了保持简单,此代码使用同步请求。
   NSString *urlString   = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
   NSURL *url            = [[NSURL alloc]initWithString:urlString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response;
   NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
   NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
   Nslog(@"%@",res);

我认为你的答案应该是最佳答案,因为它似乎是访问JSON结构最快的方法。 - Porizm
2
选项不应使用两个 |,而应该使用单个 |,因为它们需要进行按位 OR 运算。 - Deepak G M
这个问题并没有询问任何关于网络请求的内容。 - Noah Gilmore

2

@rckoenes已经向您展示了如何从JSON字符串中正确获取数据。

关于您提出的问题:EXC_BAD_ACCESS几乎总是在您尝试访问已被[自动]释放的对象后出现。这与JSON [de-]序列化无关,而只是因为您获取了一个对象,然后在其被释放后访问它。它来自JSON并不重要。

有很多页面描述如何调试这个问题 - 您需要在Google(或SO)中搜索obj-c zombie objects,特别是NSZombieEnabled,它将对您帮助确定您的zombie对象的来源非常有价值。(当您释放一个对象但保留指向它的指针并尝试稍后引用它时,“Zombie”就是它所称之处。)


1

Xcode 7(Beta)上的Swift 2.0和do/try/catch块:

// MARK: NSURLConnectionDataDelegate

func connectionDidFinishLoading(connection:NSURLConnection) {
  do {
    if let response:NSDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.MutableContainers) as? Dictionary<String, AnyObject> {
      print(response)
    } else {
      print("Failed...")
    }
  } catch let serializationError as NSError {
    print(serializationError)
  }
}

1

注意:针对Swift 3。 你的JSON字符串返回的是数组而不是字典。请尝试以下操作:

        //Your JSON String to be parsed
        let jsonString = "[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";

        //Converting Json String to NSData
        let data = jsonString.data(using: .utf8)

        do {

            //Parsing data & get the Array
            let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]

            //Print the whole array object
            print(jsonData)

            //Get the first object of the Array
            let firstPerson = jsonData[0] as! [String:Any]

            //Looping the (key,value) of first object
            for (key, value) in firstPerson {
                //Print the (key,value)
                print("\(key) - \(value) ")
            }

        } catch let error as NSError {
            //Print the error
            print(error)
        }

0
#import "homeViewController.h"
#import "detailViewController.h"

@interface homeViewController ()

@end

@implementation homeViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.frame = CGRectMake(0, 20, 320, 548);
    self.title=@"Jason Assignment";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self clientServerCommunication];
}

-(void)clientServerCommunication
{
    NSURL *url = [NSURL URLWithString:@"http://182.72.122.106/iphonetest/getTheData.php"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
    if (connection)
    {
        webData = [[NSMutableData alloc]init];
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];

    /*Third party API
     NSString *respStr = [[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding];
     SBJsonParser *objSBJson = [[SBJsonParser alloc]init];
     NSDictionary *responseDict = [objSBJson objectWithString:respStr]; */
    resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:@"result"]];
    NSLog(@"resultArray: %@",resultArray);
    [self.tableView reloadData];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [resultArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"designation"];

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"]]];
cell.imageview.image = [UIImage imageWithData:imageData];

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
     //Create the next view controller.
    detailViewController *detailViewController1 = [[detailViewController alloc]initWithNibName:@"detailViewController" bundle:nil];

 //detailViewController *detailViewController = [[detailViewController alloc] initWithNibName:@"detailViewController" bundle:nil];

 // Pass the selected object to the new view controller.

 // Push the view controller.
 detailViewController1.nextDict = [[NSDictionary alloc]initWithDictionary:[resultArray objectAtIndex:indexPath.row]];
 [self.navigationController pushViewController:detailViewController1 animated:YES];

    // Pass the selected object to the new view controller.

    // Push the view controller.
  //  [self.navigationController pushViewController:detailViewController animated:YES];
}



@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    empName.text=[nextDict valueForKey:@"name"];
    deptlbl.text=[nextDict valueForKey:@"department"];
    designationLbl.text=[nextDict valueForKey:@"designation"];
    idLbl.text=[nextDict valueForKey:@"id"];
    salaryLbl.text=[nextDict valueForKey:@"salary"];
    NSString *ImageURL = [nextDict valueForKey:@"image"];
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
    image.image = [UIImage imageWithData:imageData];
}

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