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

爷,独闯天下 提交于 2019-12-03 13:12:09

问题


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.


回答1:


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.


来源:https://stackoverflow.com/questions/1275883/generating-a-json-payload-for-post-http-request-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!