Pass object as a parameter to wcf service in Objective C on iOS

前端 未结 2 344
醉梦人生
醉梦人生 2020-12-17 06:37

I have a wcf service which accepts a parameter like this:

[DataContract]
public class Person
{
    [DataMember]
    public int ID { get; set; }

    [DataMem         


        
相关标签:
2条回答
  • 2020-12-17 07:07

    (From memory only here!)

    Try setting the body of the request thus:

    { person: { ID: 1, Name: "Joe", Family: "Bloggs" } }

    And then remember to send the Content-Type header as application/json, as well as making sure you use the POST method.

    I'm sorry I can't actually give you the actual code for doing this - I'm not an objective-c developer.

    0 讨论(0)
  • 2020-12-17 07:09

    Something like this code should work:

    NSArray *propertyNames = [NSArray arrayWithObjects:@"ID", @"Name", @"Family", nil];
    NSArray *propertyValues = [NSArray arrayWithObjects:@"123", @"joe", @"smith", nil];
    
    NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyValues forKeys:propertyNames];
    NSMutableDictionary* personObject = [NSMutableDictionary dictionary];
    [personObject setObject:properties forKey:@"person"];
    
    NSString *jsonString = [personObject JSONRepresentation];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.217/JSON/Service1.svc/InsertPerson"]];
    [request setValue:jsonString forHTTPHeaderField:@"json"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];
    
    NSError *errorReturned = nil;
    NSURLResponse *theResponse =[[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
    if (errorReturned) {
        //...handle the error
    }
    else {
        NSMutableString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        //...do something with the returned value
    
        [retVal release];
    }
    [theResponse release];
    
    0 讨论(0)
提交回复
热议问题