我需要向服务器发送一些细节。我使用了以下代码:
NSString *add1=@"";
NSString *pin=@"";
NSString *add2=@"";
NSString *total=tot;
NSString *tax1=tax;
NSString *json=[NSString stringWithFormat:@"id: %@ menuname: %@ price: %@ quantity: %@ spiceness: %@",ids,mname,mprice,mquan,mspice];
// NSLog(@"JSON %@",json);
NSString *info=[NSString stringWithFormat:@"cname: %@ ad1: %@ ad2: %@ pincode: %@ pher: %@ cmailadress: %@ res_id: %d details: %@ maintotal: %@ tax: %@ pdate:%@ ptime: %@ sffers:%@ specialinstructions:%@",personName,add1,add2,pin,phno,emailid,1,json,total,tax1,pdate,ptime,offr,sinstr];
NSLog(@"JSON %@",info);
NSString *jsonResponse=[info JSONRepresentation];
NSString *stringToAppend = @"?&method=sder&res_id=1&orr=";
NSString *newURLAsString = [NSString stringWithFormat:@"%@%@%@",URL,stringToAppend,jsonResponse];
NSURL *url = [NSURL URLWithString:newURLAsString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonResponse UTF8String] length:[jsonResponse length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
// receivedData = [[NSMutableData data] retain];
}
使用时出现以下错误:
-JSONRepresentation failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=4 \"Not valid type for JSON\" UserInfo=0x792bd80 {NSLocalizedDescription=Not valid type for JSON}"
答案 0 :(得分:1)
调用JSONRepresentation时应该使用NSDictionary。您的信息是NSString。
这样做:
NSString* jsonString = [jsonDict JSONRepresentation];