如何使用NSDictionary将Json结构传递给Webservice

时间:2015-11-02 08:33:14

标签: objective-c

我需要将JsonObject传递给web服务,现在我发现我应该使用NSDictionary,我试过的是:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"myurl"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                         @"a@aaa.com", @"Email",
                         @"123", @"Phone",
                         @"123", @"Mobile",
                         @"a", @"Name",
                         @"a", @"Surname",
                         @"a", @"AddressType",
                         @"a", @"Address",
                         @"1", @"StreetNumber",
                         @"A", @"InternalStreetNumber",
                         @"3", @"ZIPCode",
                         @"a", @"City",
                         @"a", @"ProvinceCode",
                         nil];



    NSError *error;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
    [request setHTTPBody:postData];

    // Create the NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];

但它不起作用,Webservice也没有返回任何内容,问题是我的结构应该是这样的:

userData:{
    Email: "a@aaa.com",
    Phone: "123",
    Mobile: "123",
    Name: "name",
    Surname : "surname",
    AddressType: "a",
    Address: "a",
    StreetNumber: "12",
    InternalStreetNumber: "B",
    ZIPCode: "123",
    City: "a",
    ProvinceCode: "a"
}

我无法理解如何重建这样的结构。我需要使用NSDictionary吗?我怎么可能解决这个问题?

2 个答案:

答案 0 :(得分:0)

要将NSDictionary作为json对象发送,您需要创建适当的字典结构。

首先转换为NSData。之后转换为NSString并发布为json对象。

在您的示例中:

创建字典:

NSDictionary *tmp;

然后:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error:&error];

转换为NSData后,您需要将其转换为NSString

NSString *jsonString = [[NSString alloc] initWithData:jsonDataencoding:NSUTF8StringEncoding];

jsonString可以作为json对象发送到Web服务中。

答案 1 :(得分:0)

你可以试试这个

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [request setTimeoutInterval:Request_TimeOut_Time];

     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    // Set post body
    if (postDict) //you dictionary
        [request setHTTPBody:[[postDict JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]];