1

I am currently sending some simple json from an iOS app to server using the following:

NSData *jsonData = [@"{ \"item\": \"hat\" }" dataUsingEncoding:NSUTF8StringEncoding];

I would like to add a bunch of other fields and values.

What would be the appropriate syntax to include more fields?

Something like

 NSData *jsonData = [@"{ \"item\": \"hat\",\"id\":2,\"color\":\"blue\" }" dataUsingEncoding:NSUTF8StringEncoding];

Or is there a better way to do this such by sending a dictionary?

3
  • 2
    Why not create an NSDictionary with the values you want. Then convert the dictionary to a JSON string to send to the server? Commented Nov 4, 2015 at 18:46
  • As @rmaddy said, create an NSDictionary and serialise it using NSJSONSerialization class (You'll get NSData) Commented Nov 4, 2015 at 18:47
  • 1
    JSON should really only be considered as a serialization method, not a data structure. Build an appropriate data structure, then serialize it for delivery. Commented Nov 4, 2015 at 18:57

2 Answers 2

1

Creating the Dictionary:

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:'Value' forKey:'Key']; //adding values

You can use JSONKit

convert NSDictionary to Json string like so:

NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil];

or you can use SBJson

NSString *jsonString = [dictionary JSONRepresentation];

and you can do it without third party framework:

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput 
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
Sign up to request clarification or add additional context in comments.

Comments

0

first create an NSDictionary containing the required fields and the serialize it to JSON :

NSDictionary *package = @{@"item":@"hat",@"id":2,@"color":@"blue"};
NSData *data = [NSJSONSerialization dataWithJSONObject:package 
                                    options:0 error:&error];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.