How can i fetch value from Json response in Objective -C

前端 未结 6 786
时光取名叫无心
时光取名叫无心 2021-02-11 11:40

I have a problem with fetching data from Json response.

Here is an example data structure :

(
     {
        AT = \"\";
        DId = 0;
            


        
6条回答
  •  孤城傲影
    2021-02-11 12:33

    You can use KVC to access the nested properties in the JSON. You need to know about KVC and dot syntax and Collection operators

    Frameworks that map JSON to objects, such as RestKit rely heavily on KVC.

    Following your sample, you could get a list of all PdCatList objects:

    //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"];
    

    With this you can, for example, make a very basic object mapping (which does not take care of relationships)

    In PdCatList.h

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

    In 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
    

    After getting the json object

    NSArray *pdCatLists = [json valueForKeyPath:@"@unionOfObjects.PdCatList"];
    
    [pdCatLists enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PdCatList *each = [PdCatList listWithDictionary:obj];
    }];
    

    However, If what you want is just to flatten the json, you must use recursion and create a category similar to the following.

    In NSJSONSerialization+FlattenedJSON.h

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

    In 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
    

提交回复
热议问题