我是 ios 开发新手。我有一个看起来像的 json
{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
我的编码部分
- (BOOL)didReceiveVoiceResponseNSData *)data
{
// NSLog(@"data :%@",data);
// NSError *jsonError = nil;
////
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);
NSData *data1 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data1: %@",data1);
NSData *data2 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
NSLog(@"====%@",json);
NSLog(@"%@",[json objectForKey"result"]);
控制台日志
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] responseString: {"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] data1: <7b227265 73756c74 223a5b5d 7d0a7b22 72657375 6c74223a 5b7b2261 6c746572 6e617469 7665223a 5b7b2274 72616e73 63726970 74223a22 66726565 222c2263 6f6e6669 64656e63 65223a30 2e363332 32363731 327d2c7b 22747261 6e736372 69707422 3a227765 227d5d2c 2266696e 616c223a 74727565 7d5d2c22 72657375 6c745f69 6e646578 223a307d 0a>
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] ====(null)
2016-05-06 09:55:34.910 SpeechToTextDemo[79631:2980023] (null)
请在上面找到我的编码部分和控制台日志。请指导我如何解决这个想法。我想 tanscript 值。如何获得这个值。谢谢
Best Answer-推荐答案 strong>
您的回复不是正确的 json 格式。首先添加以下行以通过以下行删除多余的空结果字符串:
yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString"{\"result\":[]}" withString""];
然后,试试下面的代码:
yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString"{\"result\":[]}" withString""];
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");
}
关于IOS - 如何将json字符串转换为对象,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/37064371/
|