Generating a JSON payload for POST HTTP request in Objective-C
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.
Admin
Updated on June 18, 2022Comments
-
Admin almost 2 years
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.
-
Lior Frenkel about 13 yearsAviad, that's awesome. sometimes we only need short code samples to get the idea. it worth 2 hours of debugging. Thanks!
-
Aviad Ben Dov about 13 years@Hamutsi: Thanks, I just wish I got the answer mark for that one ;)
-
Lior Frenkel about 13 yearsoh i did, on April 10th, just after putting the comment :)