无法解析包含“和xcode中的空格”的URL

时间:2014-02-12 11:22:31

标签: ios json xcode

我正在尝试用以下网址解析json:

NSError *error = nil;
    NSString *sampleUrl= @"http://xbmc:xbmc@192.168.1.23:8080/jsonrpc?request={\"jsonrpc\":%20\"2.0\",%20\"method\":%20\"VideoLibrary.GetMovies\",%20\"params\":%20{%20\"filter\":%20{\"field\":%20\"playcount\",%20\"operator\":%20\"is\",%20\"value\":%20\"0\"},%20\"limits\":%20{%20\"start\"%20:%200,%20\"end\":%2075%20},%20\"properties\"%20:%20[\"art\",%20\"rating\",%20\"thumbnail\",%20\"playcount\",%20\"file\"],%20\"sort\":%20{%20\"order\":%20\"ascending\",%20\"method\":%20\"label\",%20\"ignorearticle\":%20true%20}%20},%20\"id\":%20\"libMovies\"}";
    NSLog(@"%@ ",sampleUrl);

    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:sampleUrl]];

    id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

但我得到一个错误说:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

当我在浏览器中复制我的网址时:它有效! 但是当我尝试使用xcode时却没有 我尝试将设置更改为“22%并消除\:不起作用!

我该怎么办? 谢谢

2 个答案:

答案 0 :(得分:0)

问题是sampleUrl中的字符串不是格式正确的网址(请参阅RFC 1738)。

它包含网址中不允许的各种字符,例如{"。在转换为NSURL之前,必须对这些字符进行百分比转义。

您的网址字符串究竟来自哪里?

答案 1 :(得分:-1)

这是可以产生奇迹的结果:

NSString *urlString = [NSString stringWithFormat:@"http://xbmc:xbmc@192.168.1.23:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.GetMovies\", \"params\": { \"filter\": {\"field\": \"playcount\", \"operator\": \"is\", \"value\": \"0\"}, \"limits\": { \"start\" : 0, \"end\": 75 }, \"properties\" : [\"art\", \"rating\", \"thumbnail\", \"playcount\", \"file\"], \"sort\": { \"order\": \"ascending\", \"method\": \"label\", \"ignorearticle\": true } }, \"id\": \"libMovies\"}"];
    NSLog(@"%@ ",sampleUrl);
    NSString *encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSURL *url = [[NSURL alloc] initWithString:encodedUrl];


    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:encodedUrl]];

    id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

谢谢大家的帮助;)