在IOS中从2个数组创建JSON
我正在尝试创建字典以将JSON数据发布到服务器:在IOS中从2个数组创建JSON,ios,arrays,json,nsdictionary,Ios,Arrays,Json,Nsdictionary,我正在尝试创建字典以将JSON数据发布到服务器: NSArray *keys = [NSArray arrayWithObjects:@"lat", @"lon", nil]; NSArray *values = [NSArray arrayWithObjects: orderClass.extraLat, orderClass.extraLon, nil]; NSDictionary *postDict = [NSDictionary dictionaryWithObjects:values
NSArray *keys = [NSArray arrayWithObjects:@"lat", @"lon", nil];
NSArray *values = [NSArray arrayWithObjects: orderClass.extraLat, orderClass.extraLon, nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
这给了我:
{
lat = (
"54.720746",
"54.719206",
"54.717466"
);
lon = (
"56.011108",
"56.008510",
"56.007031"
);
}
但目的是以以下格式发布来自阵列的数据:
[{"lat":"54.720746", "lon":"56.011108" },
{ "lat":"54.719206", "lon":"56.008510"},
{ "lat":"54.717466", "lon":"56.007031"}]
我需要你的帮助。
谢谢你的关注 正如我在评论中所说,你需要朝着你的目标倒退。首先是字典,然后是数组。你会得到你想要的
NSArray *keys = [NSArray arrayWithObjects:@"lat", @"lon", nil];
NSArray *lats = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSArray *lons = [NSArray arrayWithObjects:@"4", @"5", @"6", nil];
// your way (not what you want)
NSArray *values = [NSArray arrayWithObjects: lats, lons, nil];
NSDictionary *postDict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
// my recommendation based on what you want
NSMutableArray *postData = [[NSMutableArray alloc] init];
for (int i = 0; i < lats.count; i++) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[lats objectAtIndex:i] forKey:@"lat"];
[dict setObject:[lons objectAtIndex:i] forKey:@"lon"];
[postData addObject:dict];
}
及
(lldb)po postData
(
{
lat=1;
lon=4;
},
{
lat=2;
lon=5;
},
{
lat=3;
lon=6;
}
)
您正在创建一个包含两个数组的字典。您需要使用三个字典(在您的示例中,通常是“n”)创建数组。换一下台阶。谢谢你,太多了!目标实现了!
(lldb) po postDict
{
lat = (
1,
2,
3
);
lon = (
4,
5,
6
);
}
(lldb) po postData
<__NSArrayM 0x7ffb5be4d950>(
{
lat = 1;
lon = 4;
},
{
lat = 2;
lon = 5;
},
{
lat = 3;
lon = 6;
}
)