如何使用AFNetworking发布JSON参数?

时间:2015-12-23 11:30:58

标签: ios json xcode afnetworking afnetworking-2

我如何使用POST JSON AFNetworking参数?以下是示例JSON格式。提前谢谢。

{
    "application": {
        "identifier": "appDev"
    },
    "sso": {
        "version": 2.0,
        "session_expiry": 43200
    },
    "user": {
        "password": "xxxx~!@",
        "username": "xxx0min"
    },
    "coordinate": {
        "latitude": 10.9948629,
        "longitude": -169.5213749
    }
}

我成功创建了一个JSON:

NSDictionary *parameters = @{@"application": @{@"identifier": @"appDev"}, @"sso": @{@"version": @"2.0", @"session_expiry":@43200}, @"user": @{@"password":@"xxxx~!@", @"username":@"xxx0min"}, @"coordinate": @{@"latitude":@10.9948629, @"longitude":@-169.5213749}};

2 个答案:

答案 0 :(得分:9)

首先将JSON字符串转换为NSDictionary:

NSError *error;
NSData *objectData = [@"{\"1\":\"2\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&error];

然后你可以用AFNetworking发送这本字典。在版本3中,您应该使用AFHTTPSessionManager:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[manager POST:@"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Fail");
}];

答案 1 :(得分:2)

最后我找到了解决问题的方法。我正在做的是为我的JSON参数制作NSDictionary的NSDictionary。以下是完整的解决方案代码。

NSString *loginURL = @"http://myappdev.dev/login";

 NSDictionary *parameters = @{@"application": @{@"identifier": @"appDev"}, @"sso": @{@"version": @"2.0", @"session_expiry":@43200}, @"user": @{@"password":@"xxxx~!@", @"username":@"xxx0min"}, @"coordinate": @{@"latitude":@10.9948629, @"longitude":@-169.5213749}};

    NSLog(@"params : %@", parameters);

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:loginURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON Successsss: %@", responseObject);
        NSLog(@"operation Successsss: %@", operation);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error laaa: %@", error);
    }];