如何从这个json获得第一个“hls”。我的源代码是搜索hls的值并显示它。但它得到了第二个“hls”...... JSON数据是:
{
"mbsServer": {
"version": 1,
"serverTime": 1374519337,
"status": 2000,
"subscriptionExpireTime": 1575057600,
"channel": {
"id" : 47,
"name" : "Yurd TV",
"logo" : "XXXX",
"screenshot" : "XXXXXXX",
"packageId" : 0,
"viewers": 1,
"access": true,
"streams" : [
{
"birate" : 200,
"hls" : "XXXXXXXX",
"rtsp" : "XXXXXXX"
},
{
"birate" : 500,
"hls" : "XXXXXXX",
"rtsp" : "XXXXXX"
}
]
}
} }
我的代码是:
@implementation ViewController - (IBAction)play:(id)sender {
NSData *JSONData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"XXXXXX"]];
NSObject *json = [JSONData objectFromJSONData];
NSArray *streams = [json valueForKeyPath:@"mbsServer.channel.streams"];
for (NSDictionary *stream in streams)
{
NSString *str = [[NSString alloc]initWithString:[stream valueForKey:@"hls"]];
videoURL = [NSURL URLWithString:str];
}
NSURLRequest *req = [NSURLRequest requestWithURL:videoURL];
[_stream loadRequest:req];
}
答案 0 :(得分:0)
问题是你的循环。 “流”中有两个流对象,如JSON对象中的[]所示,这意味着它是一个数组,并且填充了两个值。您正在迭代这两个对象,并始终获取第二个对象。手动选择您想要的对象,而不是迭代它们,并自动陷入最后一个值。
而不是:
for (NSDictionary *stream in streams)
{
NSString *str = [[NSString alloc]initWithString:[stream valueForKey:@"hls"]];
videoURL = [NSURL URLWithString:str];
}
你可能想要这个:
NSArray *arrayOfStreams = [json valueForKeyPath:@"mbsServer.channel.streams"];
NSDictionary *stream = [arrayOfStreams objectAtIndex:0];
NSString *str = [[NSString alloc]initWithString:[stream valueForKey:@"hls"]];
videoURL = [NSURL URLWithString:str];
有用的: