0

如何从这个 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];

}

4

1 回答 1

0

问题是你的 for 循环。如 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];

有帮助:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html

于 2013-07-22T19:39:43.607 回答