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

后端 未结 1 903
醉梦人生
醉梦人生 2021-02-04 17:19

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:

相关标签:
1条回答
  • 2021-02-04 17:30

    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.
    
    0 讨论(0)
提交回复
热议问题