【问题标题】:iPhone:Http POST JSON methodiPhone:Http POST JSON 方法
【发布时间】:2012-02-27 09:41:09
【问题描述】:

我需要向服务器发送一些详细信息。我使用了以下代码:

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}"

【问题讨论】:

  • 错误说明了一切......

标签: iphone objective-c ios json http-post


【解决方案1】:

在调用 JSONRepresentation 时应该使用 NSDictionary。你的信息是 NSString。

这样做:

NSString* jsonString = [jsonDict JSONRepresentation];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多