在Objective-C中为POST HTTP请求生成JSON负载 [英] Generating a JSON payload for POST HTTP request in Objective-C

查看:131
本文介绍了在Objective-C中为POST HTTP请求生成JSON负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都没有任何示例代码来创建JSON有效负载,以在Objective-C中作为HTTP POST请求发送吗?我想要生成的json有效负载示例如下:

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\"}

我正在使用从以下网站下载的json-framework: http://code.google .com/p/json-framework/

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

任何示例代码都将不胜感激.

Any sample code would be greatly appreciated.

推荐答案

您已经在使用json-framework,所以完成了一半的工作.

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

此框架可以采用任何键值编码兼容的对象并将其转换为JSON.只要支持KVC,它就可以是Core Data对象,NSDictionary对象以及任何任意对象.

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.

此外,json-framework添加了一个类别,该类别使您可以使用JSONRepresentation消息从这些对象中获取JSON字符串.

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

因此,假设您想使用NSDictionary,则可以编写:

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.

这篇关于在Objective-C中为POST HTTP请求生成JSON负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆