繁体   English   中英

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

[英]IOS - How to convert json string into object

我是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价值观。 如何获得这个值。 谢谢

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

使用此代码它将帮助您转换您的响应字符串

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

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

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);
}

我希望它会帮助你。

您的函数中已经有数据作为参数

那么为什么你将它转换为字符串并再次返回数据

- (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");
}

}

试试这个可能会帮助你 -

 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");
    }

您的 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]; 要知道怎么回事。

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

它是我对我的问题的重复答案,但它非常有用。 在这里访问我的问题

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

  • 粘贴 Json Accelerator >> 单击 Generate and Save With Your Modelname。

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


像这样使用 >>>例如你的 JSON Respoce 字典是

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
  • 创建 Employee 数组,然后使用创建的模型类创建对象,如下面的代码,您必须使用For loopenumerateObjectsUsingBlock任何一个来创建,然后添加到可变数组中。

     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 对象类以在开发中的任何地方解析数据。

试试这个代码

- (BOOL)didReceiveVoiceResponse:(NSData *)data
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"Dict=%@",dict);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM