【发布时间】:2013-01-10 21:49:20
【问题描述】:
我正在使用这样的 AFNetworking 工具使用 Web 服务:
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self GotJSONSuccess:JSON :response ];
} failure: nil ];
[operation start];
Web 服务响应并给我以下 json:
[
{
"statusid": 1,
"statusdesc": "ASSIGNED"
},
{
"statusid": 2,
"statusdesc": "COMPLETED"
},
{
"statusid": 3,
"statusdesc": "IN TRANSIT"
},
{
"statusid": 4,
"statusdesc": "DELAYED"
},
{
"statusid": 5,
"statusdesc": "ON HOLD"
}
]
我正在使用以下内容尝试解析 json:
- (void)GotJSONSuccess: (NSString*) JSON : (NSHTTPURLResponse*) response
{
NSString *newString = [NSString stringWithFormat:@"%@",JSON];
NSLog(@"response: %@", JSON);
NSData* data = [newString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error){
NSLog(@"error is %@", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys){
NSLog(@"%@ is %@",key, [jsonObjects objectForKey:key]);
}
}
但是代码落入错误块并且输出是 “操作无法完成。(Cocoa 错误 3840。)”
我在解析这个简单的 json 时做错了什么?
有没有比我现在采用的更好的解析方法?
如果可能,我想坚持使用原生 iOS 类和方法进行解析。
【问题讨论】:
-
如果你查看FoundationErrors.h(或者只是搜索你的项目,包括链接的框架,3840,这就是我所做的)你会看到错误对应于NSPropertyListReadCorruptError。什么是 kNilOptions?
-
Jesse - 知道如何绕过 NSPropertyListReadCorruptError 吗?这是否表明上面的 JSON 格式有问题?
-
Siddharth - 我最初的问题仍然是调用 NSJSONSerialization 行时出现错误。上面代码中是否有任何看起来不正确的内容可能导致它无法序列化?
标签: ios json parsing afnetworking