JSON格式有时不一样,如何从不同的JSON格式中提取信息?

时间:2017-11-08 13:33:59

标签: objective-c arrays json string nsscanner

我正在使用此功能从 Youtube 获取自动建议。

  

http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=Like&format=5&alt=json

["Tire",[["tired",0],["tired lyrics",0],["tired alan walker remix",0],["tired remix",0],["tired alan walker cover",0],["tired of being sorry enrique iglesias",0],["tire",0],["tired cover",0],["tiren mati kemaren full movie",0],["tired of talking",0]],{"k":1,"q":"raN20uYZUrouYBB7VsB396HlA88"}]

正如您从上面可以看到从上面提取信息,我使用此代码从 JSON array 中提取疲倦,疲惫的歌词,疲惫的阿兰沃克等信息。

NSString *json = nil;
    NSScanner *scanner = [NSScanner scannerWithString:str];
    [scanner scanUpToString:@"[[" intoString:NULL]; // Scan to where the JSON begins
    [scanner scanUpToString:@"]]" intoString:&json];

    NSLog(@"json before = %@", json);
            //The idea is to identify where the "real" JSON begins and ends.
    json = [NSString stringWithFormat:@"%@%@", json, @"]]"];

但有时 JSON array 可能是这种格式,如下所示。

["Like",[["likey",0,[131]],["likey twice lyrics",0,[3]],["likey dance",0,[3]],["likey dance practice",0,[3]],["likey live",0,[3]],["like i\u0027m gonna lose you",0],["like ooh ahh",0],["like a boss",0],["like a g6",0],["like a stone",0]],{"k":1,"q":"9DuLDtNkAUfZ2X9AVZN90t0Zxlw"}]

我怎样才能提取上述例子中的信息,比如likey,likey两次歌词?

1 个答案:

答案 0 :(得分:1)

NSScanner不是将原始JSON转换为有用数据的最佳API。

使用原生JSON API NSJSONSerialization

可以获得最佳效果

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

json对象可以在此处投射到NSArray

其中数据是来自响应的原始数据。

另见this answer