【问题标题】:How can i fetch value from Json response in Objective -C如何从 Objective-C 中的 Json 响应中获取值
【发布时间】:2013-08-02 13:17:09
【问题描述】:

我在从 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;
    },
)

我将如何解析结果结构? 我想直接获取值列表。如果我在元组中有多个值,例如执行者 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);

            }


        }


    }

【问题讨论】:

  • 我看到了你的问题,发现你总是为每一个新的JSON 回复提出一个新问题。
  • for(int i=0;i
  • 看看答案:stackoverflow.com/a/17025824/1603072。它可以帮助您了解 JSON 解析是什么。

标签: iphone ios objective-c json ios5


【解决方案1】:

试试这个...

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 响应中获取某些对象的值的 Answer。

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


    了解概念。这取决于您在JSON 中的内容。如果它是一个数组([ ] 中的值),那么您必须保存在NSArray 中,如果它是一个字典({ } 中的值),则另存为NSDictionary,如果您有单个值,如字符串、整数、双精度那么你必须使用适当的 Objective-C 数据类型来保存它们。

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

    【讨论】:

      【解决方案3】:

      使用 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.
      }
      

      【讨论】:

        【解决方案4】:
        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:@""];
        

        【讨论】:

          【解决方案5】:

          您必须添加 JSON 框架,将字符串解析为 NSDictionary。 使用来自here的压缩文件

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

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

            NSMutableDictionary *dictResponse = [strResponse JSONValue];
            

          【讨论】:

          【解决方案6】:

          您可以使用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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-08-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多