0

I'm not strong in programming and as it seems facing with quite simple problem. I can't figure out how to post data on server through REST Request with json. Format that has to be accepted is

{
    "date": "2012-12-20 12:00:00",
    "address": "asd",
    "name": "asdasdasdasdasd",
    "shipping_date": "2012-12-20 12:00:00",
    "receiver_phone": "123456789",
    "customer_phone": "123456789",
    "total_price": "1234",
    "items": {
        "1": {
            "item_id": "1",
            "quantity": "1",
            "type": "1",
            "color_id": "0"
        }
    }
} 

I found an article Post data in Objective C using Json but can't format my string properly.

Community
  • 1
  • 1
Asike
  • 309
  • 5
  • 14
  • 1
    You can try using popular networking libraries like AFNetworking, RestKit etc. They make this kind of RESTful webservices dirt simple. Even if you are not using them you can form an NSDictionary instance with all the values. I think the value of items is an array. Then post the data of dictionary to the postData of request. – Anupdas Mar 04 '13 at 17:00
  • NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"2013-03-03 12:12:12", @"date", @"asd", @"address",[NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"item_id", @"1", @"quantity", @"1", @"type", @"0", @"color_id", nil], @"1", nil], @"items",nil]; – Asike Mar 04 '13 at 17:03
  • Yes. I would give you an answer. – Anupdas Mar 04 '13 at 17:04

3 Answers3

0

It looks like that post is exactly what you want, minus the formatting bit. JSONKit is a very simple class to use. I find it more powerful than NSJSONSerialization. But for this, I will stich NSJSONSerialization:

// create a dictionary with the structure you want
NSDictionary *dict = @{
    @"date":@"2012-12-20 12:00:00",
    @"address":@"asd",
    @"name":@"asdasdasdasdasd",
    @"shipping_date":@"2012-12-20 12:00:00",
    @"receiver_phone":@"123456789",
    @"customer_phone":@"123456789",
    @"total_price": @"1234",
    @"items": @{
        @"1": @{
            @"item_id": @"1",
            @"quantity": @"1",
            @"type": @"1",
            @"color_id": @"0"
        }
    }
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:nil error:&error];

if ( error ) {
    // handle accordingly
}
else if ( jsonData != nil ) {
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF*Encoding];
    // build request like example
}

Now you can use the rest of the example.

UPDATE:

I find JSONKit much more powerful than NSJSONSerialization and requires less steps, but NSJSONSerialization should produce the same results, and does not require worrying about mixing ARC and non-ARC code.

UPDATE 2:

I would recommend giving JSONKit a serious look, it is less picky (i.e. values can be an NSNumber instead of NSString). It does require setting the -fno-objc-arc flag in the build phases for JSONKit.m.

Mike D
  • 4,938
  • 6
  • 43
  • 99
  • @Asike Updated with a better example on how to create the data structure you want. – Mike D Mar 04 '13 at 17:16
  • Unfortunately JSONKit does not support Objective-C Automatic Reference Counting (ARC) – Asike Mar 04 '13 at 17:28
  • After run project. I have this: erminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary' – Asike Mar 04 '13 at 17:55
  • @Asike My bad, Fixed to make all keys and values an `NSString`. – Mike D Mar 04 '13 at 17:57
0

It would be better if you create a dictionary and then convert it to data using NSJSONSerialization.

NSDictionary *params = ...

NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:params 
                                                   options:0 
                                                     error:&error];
[request setHTTPBody:postData];
Anupdas
  • 10,211
  • 2
  • 35
  • 60
0
- (IBAction)registerclick:(id)sender

{

if (_password.text==_repassword.text)
{
    [_errorlbl setHidden:YES];


NSString *requstUrl=[NSString stringWithFormat:@"http://iroidtech.com/fresery/index.php?route=api/fresery/registerCustomer"];

 NSString *postString=[NSString stringWithFormat:@"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
   // _name.text,_email.text,_mobile.text,_password.text

NSData *returnData=[[NSData alloc]init];

NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];


returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];


    c=[[resp valueForKey:@"status" ]objectAtIndex:0];
    b=[[resp valueForKey:@"message"]objectAtIndex:0];