0

我在 iOS 应用程序中使用 Google api。响应是这样的:

{
    "result":[]
}

{  
   "result":[  
      {  
         "alternative":[  
            {  
               "transcript":"hello hello",
               "confidence":0.94471323
            },
            {  
               "transcript":"Hello-Hello"
            },
            {  
               "transcript":"hello jello"
            },
            {  
               "transcript":"hello hello hello"
            },
            {  
               "transcript":"hello hello."
            }
         ],
         "final":true
      }
   ],
   "result_index":0
}

我正在获取数据,但如何解析此响应?

我将其转换为NSString. 但我需要有效的结果NSArrayNSDictionary

NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

这给了我字符串结果,但如何将其转换为NSDictionary

4

1 回答 1

0
    @try
    {
        NSString *finalSpeech;
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"responseString: %@",responseString) ;

        NSRange range = [responseString rangeOfString:@"\n"];
        if (range.location != NSNotFound)
        {
            NSString *resultString = [responseString substringFromIndex:range.location];
            NSLog(@"%@",resultString);
            NSData *jsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
//            NSLog(@"dic: %@",dic) ;
            NSArray *arrResult = [dic objectForKey:@"result"];
            NSDictionary *speech = [[[arrResult objectAtIndex:0] valueForKey:@"alternative"]objectAtIndex:0];
//            NSLog(@"speech is :%@",speech);
            finalSpeech = [speech objectForKey:@"transcript"];
        }

    }
于 2016-04-09T05:32:01.793 回答