1

I am creating a JSON array using Objective C. I have never done this before but what I would like to do is create the JSON array then make a JSON pair that I use to send back in my NSURLConnection Post body.

I know how to make and send the post body.

NSData *data = // some stuff in here...

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:data];

How do I first of all create the JSON array, then how do I make the JSON pair?

halfer
  • 19,824
  • 17
  • 99
  • 186
HurkNburkS
  • 5,492
  • 19
  • 100
  • 183

2 Answers2

3

Use Apple's NSJSONSerialization

    NSArray *array = @[@"1",@"2",@"3"];
    NSData *json = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];

    //back
    array = [NSJSONSerialization JSONObjectWithData:json options:0 error:nil];
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
0

A JSON is basically an NSDictionary converted to NSData. I would suggest just using AFNetworking framework, which takes an NSDictionary as parameter and converts it to a JSON automatically.

But if you want to do the conversion yourself, you can use apples NSJSONSerialization:

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParam
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

If you want to send an array for example you do:

NSArray *requestArray = @[@"1",@"2"];
NSDictionary *requestDictionary = @{@"Array": requestArray};

This will create the following structure:

Array =     (
    1,
    2
);

If you want to later modify the requestDictionary (ex: add extra keys and objects), you just make it mutable and work with it the same way you do with NSMutableDictionaries.

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
  • you forgot to JSON encode the stuff.. this is NOT json at all – Daij-Djan Nov 18 '13 at 08:43
  • Well, you're right in a way. This isn't a JSON, this is a parameter for AFNetworking methods, I forgot to encode it because I got used to AFNetworking, which does the encoding automatically. – Lord Zsolt Nov 18 '13 at 09:04