2011-09-07 66 views
2

參數傳遞給WCF服務在目標C我有接受這樣的參數WCF服務:通行證對象在iOS

[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-字符串參數的WCF服務C但在這種情況下,我想傳遞一個Person類的實例作爲參數。我怎樣才能做到這一點?

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

回答

1

事情是這樣的代碼應工作:

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

我知道這是舊的,但,在JSONRepresentation線給我這個錯誤**「對的NSMutableDictionary沒有可見的接口聲明的選擇JSONRepresentation」 ** – gdubs

+0

敬請期待在這[SO回答](http://stackoverflow.com/questions/7143863/jsonrepresentation-for-nsmutabledictionary?answertab=votes#tab-top)看哪些是適當的庫包括。 –

+0

包含SBJson庫以使用JSONRepresentation。你可以從https://github.com/stig/json-framework得到它 – Dilip

1

(!從內存只在這裏)

嘗試將請求體這樣的:

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

然後記得到Content-Type頭髮送的application/json,以及確保您使用POST方法。

對不起,我真的不能給你這樣做的實際代碼 - 我不是一個Objective-C開發人員。