2013-08-01 3 views
-8

У меня проблема с получением данных из ответа Json.Как получить значение из ответа Json в Objective -C

Ниже приведен пример структуры данных:

(
    { 
     AT = "<null>"; 
     DId = 0; 
     DO = 0; 
     PLId = 33997; 
     PdCatList = (
         { 
       PLId = 33997; 
       PPCId = 0; 

       pdList = (
         { 
         IsDis = 0; 
         IsPS = 0; 
         IsT = 1; 
         PA = 1; 
         PCId = 119777; 
        } 
       ); 
      } 
     ); 
     PdId = 0; 
     SId = 0; 
     Sec = 1; 
    }, 
    { 
     AT = "<null>"; 
     DId = 0; 
     DO = 11; 
     Dis = 0; 
     PLId = 34006; 
     PdCatList = (
       { 

       PLId = 34006; 
       PPCId = 0; 
       pdList = (
         { 
         IsDis = 0; 
         IsPS = 0; 
         IsT = 1; 
         PA = 1; 
         PCId = 119830; 
         }, 
         { 
         IsDis = 0; 
         IsPS = 0; 
         IsT = 1; 
         PA = 1; 
         PCId = 119777; 
         } 
        ); 
       }, 

      { 
       PLId = 33997; 
       PPCId = 0; 
       pdList = (
         { 
         IsDis = 0; 
         IsPS = 0; 
         IsT = 1; 
         PA = 1; 
         PCId = 119777; 
        } 
       ); 
      } 

     ); 
     PdId = 0; 
     SId = 0; 
     Sec = 1; 
    }, 
) 

как бы я разобрать полученную структуру? Я хотел бы получить список значений напрямую. Что делать, если у меня есть несколько значений в тупеле, например, исполнитель PdCatList, pdList. Как я могу получить доступ к этим значениям? Может кто-нибудь помочь мне

мой код Thank является

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

    for(int i=0;i<[Array1 count];i++) 
    { 
     NSDictionary *dict1 = [Array1 objectAtIndex:i]; 

     NSLog(@"Array1.....%@",dict1); 

     Array2=[dict1 valueForKey:@"PdCatList"]; 

     for(int i=0;i<[Array2 count];i++) 
     { 

      NSDictionary *dict2 = [Array2 objectAtIndex:i]; 

      NSLog(@"Array2.....%@",dict2); 

      Array3=[dict2 valueForKey:@"pdList"]; 

      for(int i=0;i<[Array3 count];i++) 
      { 

       NSDictionary *dict3 = [Array3 objectAtIndex:i]; 

       NSLog(@"Array3.....%@",dict3); 

      } 


     } 


    } 
+11

Я видел ваши вопросы и обнаружили, что вы всегда сделать новый вопрос для каждого нового ' Ответ JSON. – TheTiger

+1

for (int i = 0; i <[Array1 count]; i ++) { NSDictionary * dict1 = [Array1 objectAtIndex: i]; Array2 = [dict1 valueForKey: @ "PdCatList"]; для (int i = 0; i <[Array2 count]; i ++) { NSDictionary * dict2 = [Array2 objectAtIndex: i]; Array3 = [dict2 valueForKey: @ "pdList"]; for (int i = 0; i <[Array3 count]; i ++) { NSDictionary * dict3 = [Array3 objectAtIndex: i]; } } } – Siva

+0

Посмотрите на ответ: http://stackoverflow.com/a/17025824/1603072. Это может помочь вам понять, что такое JSON Parsing. – Bhavin

ответ

3

Попробуйте это ...

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

for(int i=0;i<[Array1 count];i++) 
{ 
    NSDictionary *dict1 = [Array1 objectAtIndex:i]; 

    ATArray =[dict1 valueForKey:@"AT"]; 
    DIdArray =[dict1 valueForKey:@"DId"]; 
    DOArray =[dict1 valueForKey:@"DO"]; 
    PLIdArray =[dict1 valueForKey:@"PLId"]; 

    etc... 

    Array2=[dict1 valueForKey:@"PdCatList"]; 

    for(int i=0;i<[Array2 count];i++) 
    { 

     NSDictionary *dict2 = [Array2 objectAtIndex:i]; 

     PLIdArray =[dict2 valueForKey:@"PLId"]; 
     PPCIdArray =[dict2 valueForKey:@"PPCId"]; 

     etc… 

     Array3=[dict2 valueForKey:@"pdList"]; 

     for(int i=0;i<[Array3 count];i++) 
     { 

      NSDictionary *dict3 = [Array3 objectAtIndex:i]; 

      IsDisArray =[dict3 valueForKey:@"IsDis"]; 
      IsPSArray =[dict3 valueForKey:@"IsPS"]; 
      IsTArray =[dict3 valueForKey:@"IsT"]; 
      PAArray =[dict3 valueForKey:@"PA"]; 
      PCIdArray =[dict3 valueForKey:@"PCId"]; 
     } 
    } 
} 
2

Я думаю, что вам нужно здесь, чтобы понять, что ответ JSON скорее, чем Ответ, чтобы получить значения некоторых объектов из ваш ответ JSON.

Если вы хотите получить подробное объяснение по поводу JSON Parsing, вы можете взглянуть на NSJSONSerialization Class Reference. Здесь дается все, или вы можете взглянуть на мой Answer.


Понять концепцию. Это зависит от того, что у вас есть в вашем JSON. Если это массив (значения внутри [ ]), то вам нужно сохранить в NSArray, если это словарь (значения внутри { }), то сохраните как NSDictionary, и если у вас есть одиночные значения, такие как string, integer, double, то вам нужно сохранить их с помощью соответствующих Типы данных Objective-C.

Для некоторых простых деталей, например, вы можете проверить мой Answer от этого вопроса.

1

Использование JSONKit (https://github.com/johnezang/JSONKit):

NSString *yourJSONString = ... 
NSArray *responseArray = [yourJSONString objectFromJSONString]; 
for(NSDictionary *responseDictionary in responseArray) 
{ 
    NSString *atString = [responseDictionary objectForKey:@"AT"]; 
    ... 
    NSArray *pdCatListArray = [responseDictionary objectForKey:@"PdCatList"]; 
    ...here you can get all values you want,if you want to get more details in PdCatList,use for in pdCatListArray ,you can do what you want. 
} 
1
Use following method: 


NSDictionary *mainDict; 
SBJSON *jsonParser = [[SBJSON alloc]init]; 
    if([[jsonParser objectWithString:responseString] isKindOfClass:[NSDictionary class]]) 
    { 
     mainDict=[[NSDictionary alloc]initWithDictionary:[jsonParser objectWithString:responseString]]; 
    } 

NSDictionary *firstDict=[NSDictionary alloc]initWithDictionary:[mainDict valueForKey:@""]; 
0

Вы должны добавить структуру JSON, которая синтаксического анализа строки в NSDictionary. Используйте почтовый файл из here

  1. Открыть папку и переименовать папку Classes в "JSON".
  2. Скопировать Папка JSON и включить в свой проект.
  3. Импорт заголовка файл, как показано ниже, в контроллере, где вы хотите разбор строки JSON.

    #import "SBJSON.h" 
    #import "NSString+SBJSON.h" 
    
  4. Теперь Разбираем вашу строку ответа, чтобы NSDictionary, как показано ниже.

    NSMutableDictionary *dictResponse = [strResponse JSONValue]; 
    
+0

Уважаемые редакторы и редактирующие рецензенты, я только что узнал об этом, но вам нужно [отступы 8 пробелов в списке] (http://meta.stackexchange.com/questions/30046/how-do-i-include-a -код-блок-правого после-а-списка-без-он-токарно-в-а-блок) – FakeRainBrigand

0

Вы можете использовать KVC , чтобы получить доступ к вложенным свойств в формате JSON. Вы должны знать о KVC and dot syntax и Collection operators

Рамки, которые отображают JSON для объектов, таких как RestKit, сильно зависят от KVC.

После вашего образца, вы можете получить список всех объектов PdCatList:

//sample data 
NSArray *json = @[ 
        @{@"PLId" : @33997, 
        @"PdCatList" : @{@"PLId": @33998, 
            @"PPCId" : @1, 
            @"pdList" : @{ 
             @"PCId" : @119777 
             }} 
         }, 
        @{@"PLId" : @33999, 
        @"PdCatList" : @{@"PLId": @4444, 
            @"PPCId" : @0, 
            @"pdList" : @{ 
              @"PCId" : @7777 
              }}} 
        ]; 

//KVC 
NSArray *pdCatLists = [json valueForKeyPath:@"@unionOfObjects.PdCatList"]; 

При этом вы можете, например, сделать очень базовое отображение объекта (который не заботится о взаимоотношениях)

В PdCatList.h

@interface PdCatList : NSObject 
@property (readonly, strong, nonatomic) NSNumber *PLId; 
@property (readonly, strong, nonatomic) NSNumber *PPCId; 
+ (instancetype)listWithDictionary:(NSDictionary *)aDictionary; 
@end 

В PdCatList.m

@implementation PdCatList 
- (void)setValue:(id)value forUndefinedKey:(NSString *)key 
{ 
    @try { 
     [super setValue:value forUndefinedKey:key]; 
    } 
    @catch (NSException *exception) { 
     NSLog(@"error setting undefined key: %@, exception: %@", key, exception); 
    }; 
} 
+ (id)listWithDictionary:(NSDictionary *)aDictionary 
{ 
    PdCatList *result = [[self alloc] init]; 
    [result setValuesForKeysWithDictionary:aDictionary]; 
    return result; 
} 
@end 

После того, как объект JSon

NSArray *pdCatLists = [json valueForKeyPath:@"@unionOfObjects.PdCatList"]; 

[pdCatLists enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    PdCatList *each = [PdCatList listWithDictionary:obj]; 
}]; 

Однако, если то, что вы хотите, это просто придавить JSON, вы должны использовать рекурсию и создать категорию, аналогичный приведенному ниже.

В NSJSONSerialization + FlattenedJSON.h

@interface NSJSONSerialization (FlattenedJSON) 
+ (void)FlattenedJSONObjectWithData:(NSData *)data completionSuccessBlock:(void(^)(id aJson))onSuccess failure:(void(^)(NSError *anError))onFailure; 
@end 

В NSJSONSerialization + FlattenedJSON.m

#import "NSJSONSerialization+FlattenedJSON.h" 

@implementation NSJSONSerialization (FlattenedJSON) 
+ (void)FlattenedJSONObjectWithData:(NSData *)data completionSuccessBlock:(void (^)(id))onSuccess failure:(void (^)(NSError *))onFailure 
{ 
    NSError *error; 
    id object = [self JSONObjectWithData:data 
        options:kNilOptions 
         error:&error]; 
    if (error) 
    { 
     onFailure(error); 
    } 
    else 
    { 
     NSMutableArray *result = [NSMutableArray array]; 
     [self flatten:object 
       inArray:result]; 
     onSuccess([result copy]); 
    } 
} 
+ (void)flatten:(id)anObject inArray:(NSMutableArray *)anArray 
{ 
    if ([anObject isKindOfClass:NSDictionary.class]) 
    { 
     [((NSDictionary *)anObject) enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 
      [self flatten:obj inArray:anArray]; 
     }]; 
    } 
    else if ([anObject isKindOfClass:NSArray.class]) 
    { 
     [((NSArray *)anObject) enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
      [self flatten:obj inArray:anArray]; 
     }]; 
    } 
    else 
    { 
     [anArray addObject:anObject]; 
    } 
} 
@end 
Смежные вопросы