有一个AFHTTPClient通过AFNetworking发布json的示例吗? [英] is there an example of AFHTTPClient posting json with AFNetworking?

查看:88
本文介绍了有一个AFHTTPClient通过AFNetworking发布json的示例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一个示例,该示例如何使用 AFHTTPClient 发布json。我看到有一个postPath方法,它使用 NSDictionary ,而AFJSONEncode方法返回一个 NSData 。有没有简便的方法可以将对象序列化为 NSDictionary ,还是有使用jsonkit的简便方法?

Looking for an example of how to post json with AFHTTPClient. I see that there is a postPath method which takes an NSDictionary and the AFJSONEncode method returns an NSData. Is there an easy way to serialize an object to NSDictionary, or is there an easier way using jsonkit?

I只需将对象作为json发布到REST API。

I just need to post the object as json to a REST API.

更新:所以我尝试将字典传递过来,但似乎中断了序列化嵌套数组。

UPDATE: So I tried passing a dictionary over but it seems to break on serializing a nested array.

例如,如果我有一个对象:

For example, if I have an object:

Post* p = [[Post alloc] init];
p.uname = @"mike";
p.likes =[NSNumber numberWithInt:1];
p.geo = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:37.78583], [NSNumber numberWithFloat:-122.406417], nil ];
p.place = @"New York City";
p.caption = @"A test caption";
p.date = [NSDate date];

谁得到字典的数据如下:

who's get dictionary has data like the following:

{
    caption = "A test caption";
    date = "2011-12-13 17:58:37 +0000";
    geo =     (
        "37.78583",
        "-122.4064"
    );
    likes = 1;
    place = "New York City";

}

序列化将完全失败,或者地理区域不会序列化为数组,但序列化为字符串文字,例如( 37.78583, -122.4064);

the serialization will either just fail outright or geo will not be serialized as an array but as a string literal like ("37.78583", "-122.4064");

推荐答案

如果要发布到JSON REST API,应该有一个从对象属性到JSON键的特定映射,对吗?也就是说,服务器期望某些命名字段中的某些信息。

If you're posting to a JSON REST API, there should be a particular mapping from object property to JSON key, right? That is, the server is expecting certain information in certain named fields.

因此,您要做的是构造 NSDictionary NSMutableDictionary 以及API中使用的键及其相应的值。然后,只需将该字典传递给 AFHTTPClient 中任何请求方法的 parameters 参数。如果客户端的 parameterEncoding 属性设置为 AFJSONParameterEncoding ,则请求的正文将自动编码为JSON

So what you want to do is construct an NSDictionary or NSMutableDictionary with the keys used in the API and their corresponding values. Then, simply pass that dictionary into the parameters argument of any request method in AFHTTPClient. If the parameterEncoding property of the client is set to AFJSONParameterEncoding, then the body of the requests will automatically be encoded as JSON.

这篇关于有一个AFHTTPClient通过AFNetworking发布json的示例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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