我正在使用 AFNetworking 使用 HTTP POST 将一些 JSON 数据发送到服务器。AFNetworking 使用setParameterEncoding:AFJSONParameterEncoding
. 所以我像这样构建我的请求参数:
NSMutableDictionary* params = [NSMutableDictionary dictionary];
NSMutableArray* users = [NSMutableArray array];
for (NSDictionary *localEntity in SOMECOREDATAENTITIES)
{
// create a new dict. "user"
NSMutableDictionary* user = [NSMutableDictionary dictionary];
// add basic parameters for our user
[user setValue:[localEntity valueForKey:@"firstname"] forKey:@"first_name"];
[user setValue:[localEntity valueForKey:@"lastname"] forKey:@"last_name"];
//one level down: create a new dict. and give it some key-value pairs
NSMutableDictionary* device = [NSMutableDictionary dictionary];
[device setValue:localEntity[@"imei"] forKey:@"device_imei"];
// add the new dict. to the user
[user setValue:device forKey:@"device"];
//two levels down: create a new array and add multiple dict. to it
NSMutableDictionary* oEntitys = localEntity[@"orders"];
NSMutableArray* orders = [NSMutableArray array];
for (NSDictionary *orderEntity in oEntitys)
{
NSMutableDictionary* order = [NSMutableDictionary dictionary];
[order setValue:[orderEntity valueForKey:@"orderID"] forKey:@"order_id"];
[orders addObject:order];
}
// add the array containing multiple NSDictionarys to the user dict.
[user setValue:orders forKey:@"orders"];
// finally add our user to the users dict.
[users addObject:user];
}
// we add our users dict to the AFNetworking parameters
[params setValue:users forKey:@"users"];
// we add some more settings to the AFNetworking parameters
[params setValue:@"SOMEVALUE" forKey:@"SOMEKEY"];
如你所见,我们在这里得到了几乎所有东西:带有一些键值对的 NSDictionary,还有嵌套的 NSDictionary 对象和嵌套在 NSDictionary 中的 NSArrays。查看发送的网络流量时,我看到发送的 JSON 对象如下所示:
注意:数据发送是一个键:用户,其值为:“对象”。我无法查看那个“对象”,因为实际上它不是对象,只是一个名为“对象”的字符串!这就是这里的问题。
但是,AFNetworking 设置似乎很好(我能够深入研究“用户”对象)——我猜这只是 NSDictionary 的一个问题——因为如果我使用这样的东西进行测试:
params = @{@"users":
@{
firstname: @"SOMENAMEVALUE",
lastname: @"SOMENAMEVALUE"
},
@"SOMEKEY": @"SOMEVALUE"]
};
那么我嗅到的流量看起来是正确的:
我在这里想念什么?