我正在使用 AFNetworking 2.0
调用 REST API 并返回有效的 JSONArray
,例如:
[{"myattr": "asdf"}, {"myattr": "jklo"}]
我用这个位置解析我的responseObject
:
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &e];
奇怪的是,我的 jSONArray
(在调试器中查找)包含两个对象,但序列化程序抛出解析错误。发生的事情是一些内部对象属性被剥离了它们的刻度。例如,我看到:
[{attr: "asdf", attr2: "jklo", "attr3": "tzze"}, ...]
奇怪的是,一些属性保留了它们的刻度!
毕竟我唯一的想法是(除了这整件事是错误的)序列化器不预期 JSONArray
而是 JSONObject
。
这是我的全部代码:
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
int statusCode = [operation.response statusCode];
NSError *e = nil;
// NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &e];
NSArray *jsonArray = (NSArray *)responseObject;
NSLog(responseObject);
NSLog(jsonArray);
NSDictionary *testDic = (NSDictionary *)jsonArray[0];
[testDic objectForKey:@"name"];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
所以,毕竟我只是在寻找解析我的 JSONArray
的解决方案。 我查看了 here , here和 here但没有找到解决方案...
谢谢!
编辑
这是解析错误:
(<invalid>) <error: expected ']' error: 1 errors parsing expression
最佳答案
您不必序列化该响应,因为它已经序列化了。 Afnetworking 库在内部做所有这些事情。只需使用
NSArray *jsonArray = (NSArray *)responseObject;
代替
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableContainers error: &e];
编辑
访问内部值,例如访问asdf
。其他人也一样。
NSDictionary *testDic = (NSDictionary *)jsonArray[0];
[testDic objectForKey:@"myattr"];
关于iOS - JSON 数组的 NSJSONSerializer 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526561/