Generating a JSON payload for POST HTTP request in Objective-C

Zap picture Zap · Aug 14, 2009 · Viewed 13.2k times · Source

Does anyone have any sample code to create a JSON payload to be sent as a HTTP POST Request in Objective-C? An example of the json payload I am looking to generate looks like:

{__metadata:{\"Uri\":\"/NewLoc/\",
\"Type\":\"Location.NewLoc\"},  \"LocID\":\"100006\",
\"latitude\": \"40.123456\", \"longitude\": \"-65.876543\",
\"VisitDate\": \"\\/Date(1249909200000)\\/\", \"type\": \"S\"}

I am using the the json-framework downloaded from: http://code.google.com/p/json-framework/

Any sample code would be greatly appreciated.

Answer

Aviad Ben Dov picture Aviad Ben Dov · Aug 15, 2009

You're already using the json-framework, so that's half the work done.

This framework can take any Key-Value Coding compatible object and translate it to JSON. It could be a Core Data object, an NSDictionary object, and any arbitrary object as long as it supports KVC.

In addition, the json-framework adds a category which allows you to get a JSON string out of these objects using the JSONRepresentation message.

So, suppose you wanted to use NSDictionary, you could write:

NSMutableDictionary* jsonObject = [NSMutableDictionary dictionary];
NSMutableDictionary* metadata = [NSMutableDictionary dictionary];
[metadata setObject:@"NewLoc" forKey:@"Uri"];
[metadata setObject:@"Location.NewLoc" forKey:@"Type"];
[jsonObject setObject:metadata forKey:@"__metadata"];
[jsonObject setObject:@"100006" forKey:@"latitude"];
// ... complete the other values
// 
NSString* jsonString = jsonObject.JSONRepresentation;
// jsonString now contains your example strings.