我需要将此数组作为参数传递给 SOAP API。后端人员是构建 API (C#/.NET) 的新手,我以前从未实现过这种 API。有 4-5 个与此相关的 SO 问题。但它们都不是我查询的解决方案。
NSArray *arr = [NSArray arrayWithObjects:@"1",@"2", nil];
NSString *soapURL = @"http://tempuri.org/IService1/addRecord";
NSString *soapBody = [NSString stringWithFormat:@"<addRecord xmlns=\"http://tempuri.org/\">"
"<id>%@</id>"
"<title>%@</title>"
"<record>%@</record>"
"</addRecord> \n” ,@“1”,@“abc", arr ];
NSLog(@"%@",soapBody);
错误:
value in string The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'addRecord'. End element 'record' from namespace 'http://tempuri.org/' expected. Found text '( 1, 2 )'.
有一件事我开始知道我不能将数组直接传递给 soapBody
。有什么选择?
API 在后端运行良好。
最佳答案
一些评论:
NSArray *arr = [NSArray arrayWithObjects:@"1",@"2", nil];
请改写现代形式:
NSArray *arr = @[@"1",@"2"];
此外,您的问题中包含错误类型的引号 ( “1”
)。确保使用常规引号,即 "
.
当您将“stringWithFormat”与 %@ 一起使用并提供一个数组时,您必须了解您得到的是什么。让我们试试:
NSArray *arr = @[@"1",@"2"];
NSString *str = [NSString stringWithFormat:@"<%@>", arr];
NSLog(@"%@", str);
结果是:
<(
1,
2
)>
意思是你的<record>
之间和 </record>
你插入了两个用逗号分隔并用括号括起来的数字,加上一些 \n
.
这是您的服务器所期望的吗?
所以我没有解决你的问题,但你必须以正确的方式格式化你的字符串并使用你的 NSLog 命令验证它。希望对您有所帮助。
编辑
例如,如果您需要提供 <value>...</value>
内的数组值比你能做到的:
NSArray *arr = @[@"1", @"2"];
NSMutableString *mStr = [NSMutableString string];
for (NSString *value in arr) {
[mStr appendFormat:@"<value>%@</value>", value];
}
NSLog(@"<record>%@</record>", mStr);
结果将是
<record><value>1</value><value>2</value></record>
关于ios - 如何将数组传递给 SOAP API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519284/