【问题标题】:AFNetwork with ASP.net Web serviceAFNetwork 与 ASP.net Web 服务
【发布时间】:2012-08-30 04:47:04
【问题描述】:

我使用 getPath 方法调用我的网络服务,如下所示:

[[AFTwitterAPIClient sharedClient] getPath:@"GetWineCategoryList"
                                parameters:parameters success:^(AFHTTPRequestOperation *operation, id JSON) {
                                    NSLog(@"JSON = %@",JSON);
                                    NSMutableArray *mutableTweets = [NSMutableArray arrayWithCapacity:[JSON count]];
                                    for (NSDictionary *attributes in mutableTweets) {
                                        Tweet *tweet = [[Tweet alloc] initWithAttributes:attributes];
                                        [mutableTweets addObject:tweet];
                                    }

                                    if (block) {
                                        block([NSArray arrayWithArray:mutableTweets], nil);
                                    }
                                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                    if (block) {
                                        block([NSArray array], error);
                                    }
                                }];

它总是输出为 NSData。如果我将此 NSData 转换为字符串,我会得到一个 JSON 字符串。

JSON = <5b7b2243 61746567 6f72794e 616d6522 3a224f54 48455222 7d2c7b22 43617465 676f7279 4e616d65 223a2252 4544227d 2c7b2243 61746567 6f72794e 616d6522 3a22524f 5345227d 2c7b2243 61746567 6f72794e 616d6522 3a225748 49544522 7d5d>

为什么不转换成 NSArray?

【问题讨论】:

    标签: objective-c json afnetworking


    【解决方案1】:

    您可以使用NSJSONSerialization Class 将您的 NSData 对象转换为 NSArray。

    NSArray *array = (NSArray*)[NSJSONSerialization JSONObjectWithData:JSON 
                                                     options:0
                                                       error:&error];
    

    这假设您知道您的 JSON 是数组类型而不是字典类型。

    【讨论】:

    • 是的,这可行,但 AFNetwork 不应该自动为我执行此操作。我在 Twitter 的 API 上使用了相同的方法,效果很好
    • AFNetworking 对响应的格式一无所知,这就是为什么将响应作为原始数据 (NSData) 提供的原因。您可以适当地转换它。
    • 要让它自动工作,您不需要在 AFNetwork 中使用 JSON 特定的子类吗?
    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 2015-12-02
    • 2010-12-04
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多