如何将NSArray发送到Web服务
我没有成功将NSArray发送到Web服务。
不调用服务方法。 但其他服务方法称之为工作。
Web服务方法是:
[WebMethod] public int Method(IList items){...
我的数组中充满了对象项目:
@interface Item : NSObject { double prop1; double prop2; double prop3; } @property double prop1; @property double prop2; @property double prop3;
从目标c我尝试发送这样的数据:
NSString *soapMsg = [NSString stringWithFormat: @"" "" "" "" "" "%@" "" "" "" "", myArray ]; NSURL *url = [NSURL URLWithString: @"http://...."]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [req addValue:@"http://www.mysite.com/Method" forHTTPHeaderField:@"SOAPAction"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [req setHTTPMethod:@"POST"]; [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (conn) { webData = [NSMutableData data]; }
UPDATE
当我像这样制作数组时:
NSArray * myArrDate = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
和做:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArrDate options:0 error:nil];
有用。 但是我有一个带有对象的数组User
具有以下属性: UserId, FirstName, LastName, Email, Username, DisplayName, Country, City
等。当我尝试上面的代码时, 用户数组的应用程序崩溃了。
您可以将NSArray
发送到webservice
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding]; NSLog(@"FemaleFriendList:\n%@", jsonString);
你不能将NSArray发送到webservice,但如果你想这样做,那么首先将NSArray转换为NSString,如下所示
NSString *stringDelete = [YourNSArray componentsJoinedByString:@","];
然后将NSString传递给webservice.Let我知道它是否正常工作!!!!!! Happy Coding … !!!
一种选择是使用NSJSONSerialization
将数组转换为字符串,反之亦然,这可以从iOS 5获得
NSArray *myArrDate = any Data .... NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArrDate options:0 error:nil]; if (!jsonData) { NSLog(@"error"); } else { NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; NSLog(@"%@",JSONString); }
有关详细信息,请参阅convert-nsdictionary-or-nsarray-to-json-nsstring-vs-versa链接。
您正在发送NSString(%@,myArray)作为参数,Web服务期望IList对象。 为什么不在发送之前序列化NSArray? 例如,您可以使用JSON。