nithin
nithin

Reputation: 2467

iPhone:Http POST JSON method

I need to send some details to a server.I used the following code:

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];
    }

I got the following error when used this:

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

Upvotes: 0

Views: 1578

Answers (1)

Denis Kutlubaev
Denis Kutlubaev

Reputation: 16114

You should use a NSDictionary when you call JSONRepresentation. Your info is NSString.

Do like this:

NSString* jsonString = [jsonDict JSONRepresentation];

Upvotes: 1

Related Questions