iOS 中的 JSON 发布不起作用(.NET 服务器)
Posted
技术标签:
【中文标题】iOS 中的 JSON 发布不起作用(.NET 服务器)【英文标题】:JSON posting in iOS not working (.NET server) 【发布时间】:2013-05-03 11:01:34 【问题描述】:无法向 .NET 服务器发送请求。
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *postURL = [NSURL URLWithString: @"SOME URL"];
NSError *error=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
输出是:
"CreatedBy":"","EmailAddress":"devanrajupericherl@gmail.com","Zipcode":"","FirstName":"devan","DeviceCategoryID:":"","State":"","CustomerTypeID:":"",.......... like this.....
但它的Json对象必须是:
(CreatedBy:"",EmailAddress:"devanrajupericherl@gmail.com",Zipcode:"",FirstName:"devan",DeviceCategoryID::"",State:"",CustomerTypeID:"" )
我正在使用 .Net 服务器进行发帖。
请求未发布到服务器。请任何人帮助我。
【问题讨论】:
输出看起来正确。请花 10 分钟学习JSON format。如果您无法在服务器端解析此 json,则问题出在其他地方。 您可以随时使用json.parser.online.fr 来验证您的输出。 【参考方案1】:NSString *urlString = @"Your Web Service URL";
NSString *parameterString = @"XYZ";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
// parameter
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"parameter_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameterString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"returnString %@",returnString);
【讨论】:
以上是关于iOS 中的 JSON 发布不起作用(.NET 服务器)的主要内容,如果未能解决你的问题,请参考以下文章
.NET 6 的 System.Text.Json 源代码生成不起作用