How to generate JSON programmatically using the JSON Framework for iPhone

I am creating an application in which I need to send JSON to a server to get a response.

How to generate JSON using the JSON Framework for iPhone?

What are other possible ways?

+7
source share
2 answers

Create an array or dictionary of objects representing the information you want to send via JSON. Once done, send -JSONRepresentation to the array / dictionary. This method returns a JSON string, and you send it to the server.

For example:

 NSDictionary *o1 = [NSDictionary dictionaryWithObjectsAndKeys: @"some value", @"key1", @"another value", @"key2", nil]; NSDictionary *o2 = [NSDictionary dictionaryWithObjectsAndKeys: @"yet another value", @"key1", @"some other value", @"key2", nil]; NSArray *array = [NSArray arrayWithObjects:o1, o2, nil]; NSString *jsonString = [array JSONRepresentation]; // send jsonString to the server 

After executing the above code, jsonString contains:

 [ { "key1": "some value", "key2": "another value" }, { "key1": "yet another value", "key2": "some other value" } ] 
+13
source

Create an NSMutableDictionary or NSMutableArray and populate it with NSNumbers and NSStrings. Call [<myObject> JSONRepresentation] to return a JSON string.

eg:

 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:@"Sam" forKey:@"name"]; [dict setObject:[NSNumber numberWithInt:50000] forKey:@"reputation"]; NSString *jsonString = [dict JSONRepresentation]; 
+1
source

All Articles