Как использовать NSJSONSerialization

144

У меня есть строка 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 выше и превратить его в структуру данных, о которой я упоминал?

  • 0
    ваша переменная данных, вероятно, ноль
  • 0
    Это не так, я уже проверял это.
Показать ещё 1 комментарий
Теги:
nsdictionary

11 ответов

190
Лучший ответ

Ваш корневой объект 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);
   }
}
  • 0
    Спасибо, я попробую это, но разве [JSON count] возвращать что-то вместо того, чтобы просто дать мне EXC_BAD_ACCESS?
  • 0
    Поэтому я добавил проверку if !jsonArray и распечатал ошибку. Это должно отобразить любую ошибку, которая произошла во время синтаксического анализа.
Показать ещё 10 комментариев
68

Это мой код для проверки, является ли полученный 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);
}

Я пробовал это для опций: kNilOptions и NSJSONReadingMutableContainers и работает правильно для обоих.

Очевидно, что фактический код не может быть таким образом, когда я создаю указатель NSArray или NSDictionary внутри блока if-else.

26

Это работает для меня. Ваш объект 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 с обратными косыми чертами.)

8

Ваш код кажется прекрасным, за исключением результата 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;
           }
           )
  • 0
    Что означает эта опция (NSJSONReadingMutableContainers). Я надеваю kNilOption и все работает отлично. Скажите мне цель использования этих опций
  • 0
    NSJSONReadingMutableLeaves удар в Google: NSJSONReadingMutableLeaves : «Указывает, что листовые строки в графе объектов JSON создаются как экземпляры NSMutableString».
Показать ещё 5 комментариев
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"]);
        }

Для быстрого 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"])
    }
4

Следующий код извлекает объект JSON с веб-сервера и анализирует его в NSDictionary. Я использовал API openweathermap, который возвращает простой ответ JSON для этого примера. Для упрощения этого кода этот код использует синхронные запросы.

   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);
  • 0
    Я думаю, что ваш ответ должен быть лучшим, потому что он кажется самым быстрым способом доступа к структуре JSON.
  • 2
    Варианты не должны использовать два | но один | так как они должны быть побитовыми ИЛИ.
Показать ещё 1 комментарий
2

@rckoenes уже показал вам, как правильно получить данные из строки JSON.

На вопрос, который вы задали, EXC_BAD_ACCESS почти всегда возникает, когда вы пытаетесь получить доступ к объекту после того, как он был выпущен [автоматически]. Это не относится к сериализации JSON [de-], но, скорее, просто связано с тем, что вы получаете объект, а затем получаете доступ к нему после его выпуска. Тот факт, что он пришел через JSON, не имеет значения.

Существует много-много страниц, описывающих, как отлаживать это: вы хотите использовать Google (или SO) obj-c zombie objects и, в частности, NSZombieEnabled, что окажется неоценимым для вас, помогая определить источник вашего зомби объекты. ( "Зомби" - это то, что он называл, когда вы отпускаете объект, но сохраняете указатель на него и пытаетесь ссылаться на него позже.)

1

ПРИМЕЧАНИЕ. Для Swift 3. Ваша строка JSON возвращает Array вместо словаря. Попробуйте следующее:

        //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)
        }
1

Swift 2.0 на Xcode 7 (бета) с блоком 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)
  }
}
0

Проблема связана с авторекламой объектов. NSJSONSerialization JSONObjectWithData, очевидно, создает некоторые объекты с автореализацией и передает их вам. Если вы попытаетесь перенести это на другой поток, он не будет работать, поскольку он не может быть освобожден в другом потоке.

Трюк может состоять в том, чтобы попробовать выполнить изменяемую копию этого словаря или массива и использовать его.

NSError *e = nil;
id jsonObject = [NSJSONSerialization 
JSONObjectWithData: data 
options: NSJSONReadingMutableContainers 
error: &e] mutableCopy];

Рассмотрение NSDictionary как NSArray не приведет к исключению "плохого доступа", но вместо этого, возможно, произойдет сбой при вызове метода.

Также, возможно, варианты здесь не имеют никакого значения, но лучше дать NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments, но даже если они являются автореализованными объектами, это может не решить эту проблему.

  • 0
    Дипак, вы дважды указали NSJSONReadingMutableContainers. Вы имели в виду NSJSONReadingMutableLeaves?
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];
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню