【问题标题】:How do I POST JSON data object to server?如何将 JSON 数据对象发布到服务器?
【发布时间】:2013-11-12 06:08:44
【问题描述】:

我将 NSDictionary 发布到服务器并像这样获取 NSLog:

{"User":"abc@gmail.com","cartItems":[{"productName":"Apple 5s","Qty":1,"price":"1000"}],"userDiscounts":["0001"]}

但问题是当我在服务器端检查这些数据时:

{ '{"User":"abc@gmail.com","cartItems":': { '{"productName":"Apple 4s","Qty":1,"price":"1000"}],"userDiscounts"': { '"0001"]': '' } } }

我的意思是,在服务器端获取'{ and }'。 这两个 json 字典有什么问题。

这是我的方法:

 // Convert object to data, cartDictionary holding data.
    NSData* postData = [NSJSONSerialization dataWithJSONObject:cartDictionary options:kNilOptions error:&error];

NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:combineProductUrl]];
[request setHTTPMethod:@"POST"];

[request setHTTPBody:postData];

// print json:
NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:postData
                                                 encoding:NSUTF8StringEncoding]);

【问题讨论】:

标签: ios json post


【解决方案1】:

使用 NSURLConnection 的包装器,即 AFNetworking https://github.com/AFNetworking/AFNetworking。根据你的问题

NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys: deviceCode ,@"Key 1", Value 1 , @"Key 2", Value 2 , nil];

            NSLog(@"Parameter %@",parameters);

            AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:@"http://yourbaseURL/"]];

            [client setDefaultHeader:@"contentType" value:@"application/json; charset=utf-8"];

            client.parameterEncoding = AFJSONParameterEncoding;

            NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"yourPostURL" parameters:parameters];

            AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                                 {
                                                     NSLog(@"response %@",JSON);

                                                 }
                                                                                                failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                                 {
                                                     NSLog(@"request %@",[error localizedDescription]);
                                                 }];
            [operation start];

希望对你有帮助。

【讨论】:

  • ..感谢您的宝贵时间,但我已经用不同的方法解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多