繁体   English   中英

如何使用“ var abcd =”标头解析json数据

[英]How to parse json data with “var abcd =” header

我在iOS上解析json数据文件时遇到问题。 这是来自data.json文件的示例:

var devs = [
{
"ident":"1",
"firstname":"Jan", 
"lastname":"Kowalski", 
"img":"http://www.placekitten.com/125/125", 
"tech":"iOS, HTML5, CSS, RWD",
"github":"placeholder",
"opensource":"1",
"twitter":"placeholder"
},
{
"ident":"2",
"firstname":"WacĹaw", 
"lastname":"GÄsior", 
"img":"http://www.placekitten.com/124/125",
"tech":"Android, Java, Node.js",
"github":"GÄsiorBKR",
"twitter":"wacek5565"
},

等等。

我使用“普通” json文件:

NSURLResponse *response;
NSError *myError;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL      URLWithString:@"http://somerailsapplication/posts.json"]     cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

不幸的是,这种解决方案在这种情况下不起作用。 是否有机会在下载的数据中不搜索特定字符串“ var dev = [”和最后一个“]”的情况下使此工作正常进行?

响应是JavaScript,而不是JSON,因此您将无法直接使用JSON解析器。 如果您无法更改服务器输出,最简单的方法就是按照您的建议剥离数据的开头和结尾。 您也可以将响应嵌入HTML模板中,然后在Webview中对其进行评估,但这似乎还有很多工作要做。

从获得数据的那一点开始:

NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSMutableString *dataAsString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[dataAsString deleteCharactersInRange:NSMakeRange(0, 11)];
data = [dataAsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

这会将数据转换为字符串,删除前11个字符,将其转换回数据,然后按常规进行解析。 (由于您的数据在数组中,因此我将其更改为NSArray)

暂无
暂无

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

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