IOS - 如何将json字符串转换为对象

时间:2016-05-06 04:41:04

标签: ios objective-c json

我是ios开发的新手。我有一个看起来像

的json
{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0} 

我的编码部分

- (BOOL)didReceiveVoiceResponse:(NSData *)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值。如何获得这个价值。感谢

8 个答案:

答案 0 :(得分:2)

您的回复不是正确的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");
    }

答案 1 :(得分:0)

使用此代码可帮助您转换响应字符串

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

获取值后,在Dictionary中添加接收的值 然后根据您的需要使用它

答案 2 :(得分:0)

NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data1: %@",data);

NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

if (error == nil) {

    if([dict valueForKey:@"result"]) {

        NSLog(@"%@", [[dict valueForKey:@"result"] objectAtIndex:0]);

        //you need to do loop to get all transcript data
        //NSArray *array = [[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"];

        NSString *transcript = [[[[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"] objectAtIndex:1] valueForKey:@"transcript"];

        NSLog(@"transcript = %@", transcript);
    }

} else {
    NSLog(@"Error = %@",error);
}

我希望它会对你有所帮助。

答案 3 :(得分:0)

您已将数据作为函数中的参数

然后为什么要将它转换为字符串并再次返回数据

- (BOOL)didReceiveVoiceResponse:(NSData *)data
{
//    NSLog(@"data :%@",data);
//    NSError *jsonError = nil;
   NSError *error;

   NSDictionary  *json = [NSJSONSerialization JSONObjectWithData:data options:0  error:&error];
if (error == nil) {
    // no error
 NSLog(@"====%@",json);
 NSLog(@"%@",[json objectForKey:@"result"]);
} else {
    NSLog(@"error");
}

}

答案 4 :(得分:0)

尝试这可能会对你有帮助 -

 NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];


    NSError *error = nil;
   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

    if(! error) {
        NSArray *Array1 = [dict objectForKey:@"result"];
//now you will go inside dict having key "result"
        for (NSDictionary *dict2 in Array1) {
            NSArray *Array2 = [dict2 objectForKey:@"result"];
            for (NSDictionary *dict3 in Array2) {
                NSArray *array3 = [dict3 objectForKey:@"alternative"]);
for(NSDictionary *dict4 in array3)
NSLog(@"transcript--",[dict4 objectForKey:@"transcript"]);
            }
        }

    } else {
        NSLog(@"Error");
    }

答案 5 :(得分:0)

你的json字符串格式不正确:

{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},    {"transcript":"we"}],"final":true}],"result_index":0}

这表明这两个项目应该在一个数组中,但在你的json字符串中,它们是独立的。

[
    {"result":[]},
    {"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
]

您的代码没问题,您可以将错误对象传递到[NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];以了解问题所在。

答案 6 :(得分:0)

您必须为 iOS和Android 使用对象类(模型类)生成器工具,只需复制并粘贴您的响应并从工具中获取对象类。

我的问题的重复答案,但它非常有用。visit my question here

  • AppStore(Mac AppStore)下载 JSON加速器
  • 从浏览器复制JSON响应。(响应必须是JSON验证)。

  • 粘贴在Json Accelerator中&gt;&gt;单击“生成并使用模型名保存”。

  • 选择输出语言并添加基类名称(不需要类前缀)
  • 请参阅以下生成的模型类和SubModel Classe (它自动生成所有JSON对象类)


使用此类&gt;&gt;&gt;  例如,您的JSON Respoce词典是

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
  • 制作Employee Array,然后使用下面的代码创建具有Created Model Classes的Object,你必须使用For loopenumerateObjectsUsingBlock任何一个用于create,然后使用Add in Mutable Array。

    NSArray *arrTemp = [NSArray arrayWithArray:yourResponceDict[@"employees"]];
    NSMutableArray *myMutableArray = [NSMutableArray array];
    
    [arrTemp enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        Employee *aObj = [Employee modelObjectWithDictionary:obj];
        [myMutableArray addObject:aObj];
    }];
    

此工具非常简单,可以节省时间,用于创建Json对象类,以便在开发中的任何位置解析数据。

答案 7 :(得分:0)

试试此代码

NetWatcherServer = function(handler) {
    return net.createServer(handler);
};