【问题标题】:Convert JSON array to Objective-C in iOS在 iOS 中将 JSON 数组转换为 Objective-C
【发布时间】:2016-08-30 21:33:47
【问题描述】:

我是 iOS 开发新手。我正在尝试将 JSOn 数组值转换为 Objective-C 值。我的 JSON 值是这样的:

{"result":
        [{"alternative":
                    [{"transcript":"4"},
                    {"transcript":"four"},
                    {"transcript":"so"},
                    {"transcript":"who"}],
    "final":true}],
 "result_index":0}

我试过这样:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];

NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSArray *speechArray= [speechResult valueForKey:@"result"];
NSLog(@"%@",speechArray);

NSLog(@"Response is of type: %@", [speechArray class]);

speechArray 始终为空。如何解决这个问题?
同时我想打印transcript 值。

【问题讨论】:

  • speechArray 值总是打印空值。谢谢@Avi

标签: ios objective-c json nsarray


【解决方案1】:

你应该先像这样分配你的字典-

   NSDictionary *speechResult = [[NSDictionary alloc]init];
    speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSArray *speechArray = [[NSArray alloc]init];
    speechArray= [speechResult valueForKey:@"result"];

【讨论】:

    【解决方案2】:

    试试下面的代码来获取成绩单:

        NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
    
        NSError *error = nil;
        NSDictionary *responseObj = [NSJSONSerialization
                                     JSONObjectWithData:jsonData
                                     options:0
                                     error:&error];
    
        if(! error) {
            NSArray *responseArray = [responseObj objectForKey:@"result"];
            for (NSDictionary *alternative in responseArray) {
                NSArray *altArray = [alternative objectForKey:@"alternative"];
                for (NSDictionary *transcript in altArray) {
                    NSLog(@"transcript : %@",[transcript objectForKey:@"transcript"]);
                }
            }
    
        } else {
            NSLog(@"Error in parsing JSON");
        }
    

    【讨论】:

      【解决方案3】:

      你必须在使用它之前初始化数组,

      NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
      
      NSError *error;
      NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
      
      NSArray *speechArray= [[NSArray alloc] init];
      speechArray= [speechResult valueForKey:@"result"];
      if (speechArray.count>0) {
        NSDictionary * alternativeDictn = [speechArray objectAtIndex:0];
        NSArray *alternativeAry= [[NSArray alloc] init];
        alternativeAry = [alternativeDictn objectForKey:@"alternative"];
        NSLog(@"%@",alternativeAry);
      }
      
      NSLog(@"Response is of type: %@", [speechArray class]);
      

      使用此代码,您将得到以下结果,

      (
              {
              transcript = 4;
          },
              {
              transcript = four;
          },
              {
              transcript = so;
          },
              {
              transcript = who;
          }
      )
      

      【讨论】:

      • 我想打印成绩单值。 [{"transcript":"4"}, {"transcript":"four"}, {"transcript":"so"}, {"transcript":"who"}],
      • @amsaraj 检查我的更新答案,我已根据您的需要进行了更改
      • @amsaraj 如果您遇到任何问题,请告诉我。
      • 2016-05-05 13:24:36.396 SpeechToTextDemo[18148:2489059] *** 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“***-[__NSArray0 objectAtIndex:]:空 NSArray' 的索引 0 越界 *** 第一次抛出调用堆栈:
      • @amsaraj - 你能提供你的请求网址吗,我给答案
      【解决方案4】:

      试试这个代码,

      restaurantdictionary = [NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:&e];
      
      NSMutableArray *main_array=[[NSMutableArray alloc]init];
      
      main_array=[restaurantdictionary valueForKey:@"results"];
      
      NSLog(@"main_array %@", main_array);
      

      它对我有用,希望它有帮助

      【讨论】:

        【解决方案5】:

        试试这个可能对你有帮助:-

        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
        
        NSError *error;
        NSDictionary *speechResult = [NSDictionary new];
        speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
        NSArray *speechArray = [[NSArray alloc]init];
        speechArray= [speechResult valueForKey:@"result"];
        NSLog(@"%@",speechArray);
        
        NSLog(@"Response is of type: %@", [speechArray class]);
        

        【讨论】:

          【解决方案6】:

          你有没有检查 NSDictionary (speechResult) 中的值。

          如果为nil,检查json数据是否有效。

             NSError *error;
              if ([NSJSONSerialization JSONObjectWithData:data
                                                  options:kNilOptions
                                                    error:&error] == nil)
              {
                  // Check the error here
              }else {
                  // here check whether it is a dictionary and it has key like @Bhadresh Mulsaniya mentioned.
              }
          

          如果返回 nil,则检查错误以了解问题所在。

          【讨论】:

            【解决方案7】:
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];//data is your response from server as NSData
            
            if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
                NSArray * speechArray = json[@"result"];
            }
            
            NSLog(@"speech array %@",speechArray);
            

            【讨论】:

              【解决方案8】:

              我认为问题可能在于初始化数组和字典。

              尝试这样做,

              NSDictionary *speechResult = [NSDictionary new];
              
              NSArray *speechArray = [NSArray new];
              

              希望对你有帮助..

              【讨论】:

                猜你喜欢
                • 2012-02-26
                • 2011-09-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多