2014-09-04 3 views
-1

Я пытаюсь разобрать ниже JSON, но я не получаю данные от этого JSON. В приведенном ниже JSON Я пытаюсь принести выбор, но его не получает с моим ниже кодомJSON Parsing of ios

NSString *filePathChoices = [[NSBundle mainBundle] pathForResource:@"questions" ofType:@"json"]; 

    NSData *JSONDataChoices = [NSData dataWithContentsOfFile:filePathChoices options:NSDataReadingMappedIfSafe error:nil]; 
    NSMutableDictionary *jsonObjectChoices = [NSJSONSerialization JSONObjectWithData:JSONDataChoices options:NSJSONReadingMutableContainers error:nil]; 
    NSArray *arrayChoices = [jsonObjectChoices objectForKey:@"choices"]; 

    //NSDictionary *jsonDict = [arrayChoices objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [arrayChoices objectAtIndex:indexPath.row]; 

Из этого ниже JSON я выборки выбора в Tableview

{ 
      "questions": [ 
      { 
      "question": "1. An ITM option has is priced at $3.00. The strike is at $20 and the underlying is trading at $19. What is the extrinsic value of the option?", 
      "choices": ["Ontario","New Brunswick","Manitoba","Quebec"], 
      "correctAnswer": 0 
      }, 



{ 
    "question": "2. True or False. If a trader is long some calls and long some puts, he is likely to be?", 
     "choices": ["Ontario", "New Brunswick", "Nova Scotia", "Quebec"], 
     "correctAnswer": 3 
     }, 

     { 
     "question": "3. Which of these provinces start with 'New'?", 
     "choices": ["Ontario", "New Brunswick", "Quebec", "Manitoba"], 
     "correctAnswer": 1 
     }, 

     { 
     "question": "4. Which of these begin with the word 'Man'?", 
     "choices": ["Ontario", "New Brunswick", "Quebec", "Manitoba"], 
     "correctAnswer": 3 
     }, 

     { 
     "question": "5. Which of these begin with the word 'Nova'?", 
     "choices": ["Ontario", "Nova Scotia", "British Columbia", "New Brunswick"], 
     "correctAnswer": 1 
     }, 
     ] 
    } 
+0

Это не массив. Перейдите на json.org и изучите синтаксис JSON. –

+0

Недействительно JSON - Попробуйте jsonlint.com – Paulw11

+0

проверить изменение .. –

ответ

1

Вы не можете напрямую разобрать массив значений в ячейке. Заменить код с кодом ниже, чтобы решить ее

NSString *filePathchoice = [[NSBundle mainBundle] pathForResource:@"questions" ofType:@"json"]; 

NSData *JSONData = [NSData dataWithContentsOfFile:filePathchoice options:NSDataReadingMappedIfSafe error:nil]; 
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil]; 
NSArray *array = [jsonObject objectForKey:@"questions"]; 

questions = [[NSMutableArray alloc] initWithCapacity:[array count]]; 



for (NSDictionary *dict in array) { 
    question = [[Question alloc] initWithObject:dict]; 
    [questions addObject:question]; 
} 


cell.textLabel.text = [choices objectAtIndex:indexPath.row]; 
cell.textLabel.font=[UIFont fontWithName:@"Bold" size:12]; 
+1

Ошибка объекта не для удовольствия;) Вы должны проверить, есть ли у вас какие-либо ошибки. – Matz

+0

перед отправкой ответа только я проверил его – 2014-09-04 11:51:14

0

Вашего JSON не непросроченный изменить ваш json-файл, как показано ниже, и попробуйте

{ 
    "questions": [ 
     { 
      "question": "1. An ITM option has is priced at $3.00. The strike is at $20 and the underlying is trading at $19. What is the extrinsic value of the option?", 
      "choices": [ 
       "Ontario", 
       "New Brunswick", 
       "Manitoba", 
       "Quebec" 
      ], 
      "correctAnswer": 0 
     }, 
     { 
      "question": "2. True or False. If a trader is long some calls and long some puts, he is likely to be?", 
      "choices": [ 
       "Ontario", 
       "New Brunswick", 
       "Nova Scotia", 
       "Quebec" 
      ], 
      "correctAnswer": 3 
     }, 
     { 
      "question": "3. Which of these provinces start with 'New'?", 
      "choices": [ 
       "Ontario", 
       "New Brunswick", 
       "Quebec", 
       "Manitoba" 
      ], 
      "correctAnswer": 1 
     }, 
     { 
      "question": "4. Which of these begin with the word 'Man'?", 
      "choices": [ 
       "Ontario", 
       "New Brunswick", 
       "Quebec", 
       "Manitoba" 
      ], 
      "correctAnswer": 3 
     }, 
     { 
      "question": "5. Which of these begin with the word 'Nova'?", 
      "choices": [ 
       "Ontario", 
       "Nova Scotia", 
       "British Columbia", 
       "New Brunswick" 
      ], 
      "correctAnswer": 1 
     } 
    ] } 
2

Выбор не на верхнем уровне.

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

Пример:

NSArray *questions = [jsonObjectChoices objectForKey:@"questions"]; 

Теперь получить вопрос (здесь мы берем первый)

NSDictionnary *question=[questions objectAtIndex:0] 

И затем, если вы хотите, чтобы получить выбор на этот вопрос

NSArray *choices=[question objectForKey:@"choices"]; 
-1

ОХ библиотеке я использую в своих проектах JsonModel.

Пример одной строки запроса, чтобы получить json.

[JSONHTTPClient postJSONFromURLWithString:@"http://example.com/api" 
            params:@{@"postParam1":@"value1"} 
           completion:^(id json, JSONModelError *err) { 

            //check err, process json ... 

           }]; 

Для этого: JSON

{ 
    "order_id": 104, 
    "total_price": 103.45, 
    "products" : [ 
    { 
     "id": "123", 
     "name": "Product #1", 
     "price": 12.95 
    }, 
    { 
     "id": "137", 
     "name": "Product #2", 
     "price": 82.95 
    } 
    ] 
} 

Вам нужно только подкласс JSONModel и добавить в свой файл .h:

@protocol ProductModel 
@end 

@interface ProductModel : JSONModel 
@property (assign, nonatomic) int id; 
@property (strong, nonatomic) NSString* name; 
@property (assign, nonatomic) float price; 
@end 

@implementation ProductModel 
@end 

@interface OrderModel : JSONModel 
@property (assign, nonatomic) int order_id; 
@property (assign, nonatomic) float total_price; 
@property (strong, nonatomic) NSArray<ProductModel, ConvertOnDemand>* products; 
@end 

@implementation OrderModel 
@end 

Преимущества JSONModel:

  • One line для json/или вы можете выбрать anothe r выбор метода.
  • Легко конвертировать объекты JSONModel в/из NSDictionary, текст.
  • Дополнительные параметры, прямое преобразование в указанные типы данных и пользовательскую обработку ошибок и многое другое.

Установка:

  • источник клонирования, копировать вставить папку JSONModel в свой проект.
  • Подкласс JSONModel, добавьте свойство соответсвующего из JSON в файл заголовок (будьте осторожны, если ваш JSON потенциально malformatted, вы должны использовать параметр, который инструктирует рамку , что в вашем JSON, это может быть нулевыми или отсутствуют).
  • Извлеките и проанализируйте ваш json, как в приведенном выше примере, а затем проверьте все свойства для несоответствий.

В вашем примере, у вас есть "" в плюс, как раз перед "]"

Исправленный код:

{ 
    "questions": [ 
    { 
     "question": "1. An ITM option has is priced at $3.00. The strike is at $20 and the underlying is trading at $19. What is the extrinsic value of the option?", 
     "choices": [ 
     "Ontario", 
     "New Brunswick", 
     "Manitoba", 
     "Quebec" 
     ], 
     "correctAnswer": 0 
    }, 
    { 
     "question": "2. True or False. If a trader is long some calls and long some puts, he is likely to be?", 
     "choices": [ 
     "Ontario", 
     "New Brunswick", 
     "Nova Scotia", 
     "Quebec" 
     ], 
     "correctAnswer": 3 
    }, 
    { 
     "question": "3. Which of these provinces start with 'New'?", 
     "choices": [ 
     "Ontario", 
     "New Brunswick", 
     "Quebec", 
     "Manitoba" 
     ], 
     "correctAnswer": 1 
    }, 
    { 
     "question": "4. Which of these begin with the word 'Man'?", 
     "choices": [ 
     "Ontario", 
     "New Brunswick", 
     "Quebec", 
     "Manitoba" 
     ], 
     "correctAnswer": 3 
    }, 
    { 
     "question": "5. Which of these begin with the word 'Nova'?", 
     "choices": [ 
     "Ontario", 
     "Nova Scotia", 
     "British Columbia", 
     "New Brunswick" 
     ], 
     "correctAnswer": 1 
    } 
    ] 
} 

модель, которую можно использовать для анализа этого:

@interface QuestionsFetch : JSONModel 
@property (strong, nonatomic) NSArray<QuestionModel>* questions; 

@protocol QuestionModel @end 
@interface QuestionModel : JSONModel 
@property (strong, nonatomic) NSString* question; 
@property (strong, nonatomic) NSArray<ChoicesModel>* choices; 

@protocol ChoicesModel @end 
@interface ChoicesModel : JSONModel 
@property (strong, nonatomic) NSArray* choice; 

Если у вас возникли проблемы с импортом/разбором, оставьте комментарий.