本文介绍了将对象作为参数传递给iOS上的Objective C中的wcf服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受这样的参数的wcf服务:

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

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

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Family { get; set; }
}

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, UriTemplate = "")]
int InsertPerson(Person person);

我熟悉如何使用来自Objective-C的字符串参数来使用wcf服务,但在这种情况下我想要将Person类的实例作为参数传递。我该怎么做?

I am familiar how to consume a wcf service with string parameter from Objective-C but in this case I want to pass an instance of Person class as parameter. How can I do that?

 NSString *path = [[NSString alloc] initWithFormat:@"http://192.168.0.217/JSON/Service1.svc/InsertPerson"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];

[request setHTTPMethod:@"POST"];  

[[NSURLConnection alloc] initWithRequest:request delegate:self];


推荐答案

这样的代码应该有用:

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];

这篇关于将对象作为参数传递给iOS上的Objective C中的wcf服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:20