我向Instapaper发出请求,它应该返回JSON。它返回类似于JSON的内容,但不是完全返回,如下所示:
2013-05-30 19:54:20.155 --[53078:c07] (
{
type = meta;
},
{
"subscription_is_active" = 1;
type = user;
"user_id" = --;
username = "--@gmail.com";
},
{
"bookmark_id" = 387838931;
description = "";
hash = YHwQuwhW;
"private_source" = "";
progress = 0;
"progress_timestamp" = 0;
starred = 0;
time = 1369954406;
title = "Adobe Finally Releases Kuler Color-Picking App for iPhone - Mac Rumors";
type = bookmark;
url = "http://www.macrumors.com/2013/05/30/adobe-finally-releases-kuler-color-picking-app-for-iphone/";
},那么我该如何处理它呢?即使它看起来不是有效的NSDictionary,我也可以把它转换成JSON吗?
发布于 2013-06-05 18:50:15
来自Instapaper API Docs
实例文件字符串总是以UTF8编码,并且Instapaper要求所有的输入都是UTF8。除非另有说明,否则每个方法的输出都是一个数组。默认情况下,输出数组以JSON形式返回。您可以指定一个带有回调函数名的jsonp参数,例如jsonp=myCallback,以使用JSONP并将输出包装在对指定函数的调用中。
所以你不可能得到无效的JSON!
尝试以下代码:
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL urlWithString:@"http://your-instapeper-API-link"] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id serializationJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];然后你可以记录错误的地方,或者如果结果是你所期望的:
NSLog(@"class of JSON input: %@ \n and possible error: %@",[serializationJSON class],error);当然,你应该期待数组并且没有错误。
编辑...基于coment代码:
基于docs,你应该得到数组或字典。请添加此核心,而不是您的第23行(来自here的数字):
if([JSON isKindOfClass:[NSDictionary class]]) {
NSDictionary *jsonDictionary = JSON;
NSLog(@"%@",[jsonDictionary allKeys]);
} else {
NSLog(@"JSON object class: %@",[JSON class]);
}请给我们看一下输出。
还有一件事:
你从请求中得到数组。太棒了!这是有效的JSON。所以你需要对它进行调试。正如我所说的,遗憾的是它不是一个无限制访问的公共API,所以我可以研究一下它。但是现在你必须调试你的结果。我在您的代码中看到您正在尝试访问书签。所以我查看了Bookmarks section in docs,这是某种列表(NSArray)。所以如果你不知道你想要什么结果。您应该将它们打印到日志中(或设置断点)。用这个简单的日志替换我之前更新中的代码:
NSDictionary *resultDictionary;
if([JSON isKindOfClass:[NSArray class]]) {
NSArray *jsonArray = JSON;
NSLog(@"so json is an array with %i objects",[jsonArray count]);
for(id objectInsideArr in jsonArray) {
NSLog(@"object in array [class]: %@ [value]: %@",[objectInsideArr class],objectInsideArr); //if here you find NSDictionary maybe is this dictionary you are looking for. I'm not sure what it is.
if([objectInsideArr isKindOfClass:[NSDictionary class]]) {
resultDictionary = [[NSDictionary alloc] initWithDictionary:objectInsideArr];
}
}
}发布于 2013-06-04 22:37:17
如果是我,我会编写一个自定义格式化程序将其转换为JSON格式,然后在知道NSJSONSerialization有效后使用它。你所张贴的内容根本不是有效的,它是不可能工作的。我很惊讶他们以这种格式返回它,他们是否提供了某种类型的库来使用他们的服务?
发布于 2013-06-08 17:56:48
如果你想要更简单的东西,我可以给你我的CGIJSONObject库,它将使用反射来处理JSON -你只需要将API中的键与你的类进行镜像,这样就可以了。
https://stackoverflow.com/questions/16847247
复制相似问题