如何从Objective -C中的Json响应中获取值

时间:2013-08-01 14:37:53

标签: iphone ios objective-c json ios5

从Json响应中获取数据时遇到问题。

以下是一个示例数据结构:

(
     {
        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;
    },
)

我将如何解析生成的结构? 我想直接得到一个值列表。如果我在tupel中有多个值,例如执行者PdCatList,pdList,该怎么办?我将如何访问这些值? 任何人都可以帮助我

感谢的

我的代码是

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);

            }


        }


    }

6 个答案:

答案 0 :(得分: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"];
        }
    }
}

答案 1 :(得分:2)

我认为您需要的是了解JSON响应是什么,而不是从JSON响应中获取某些对象的值的答案。

如果您想了解有关JSON解析的详细说明,那么您可以查看NSJSONSerialization Class Reference。一切都在那里,或者你可以看看我的Answer


理解概念。这取决于你JSON中的内容。如果它是一个数组([ ]内的值),那么你必须保存在NSArray,如果它是一个字典({ }内的值),那么保存为NSDictionary如果你有单个值如string,integer,double则必须使用适当的Objective-C数据类型保存它们。

有关示例的一些简单细节,您可以从此问题中查看我的Answer

答案 2 :(得分: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.
}

答案 3 :(得分: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:@""];

答案 4 :(得分:0)

您必须将解析字符串中的JSON框架添加到NSDictionary中。 使用here

中的zip文件
  1. 打开文件夹并将Classes文件夹重命名为“JSON”。
  2. 复制 JSON文件夹并包含在您的项目中。
  3. 导入标题文件,如下所示,在您要解析JSON字符串的控制器中。

    #import "SBJSON.h"
    #import "NSString+SBJSON.h"
    
  4. 现在,将您的回复字符串解析为 NSDictionary ,如下所示。

    NSMutableDictionary *dictResponse = [strResponse JSONValue];
    

答案 5 :(得分:0)

您可以使用KVC 访问JSON中的嵌套属性。您需要了解KVC and dot syntaxCollection 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