如何通过Post动态地将对象列表发送到我们的服务器

时间:2014-01-23 05:18:47

标签: ios objective-c json

如果它的单个对象能够发送但如何使用json序列化和反序列化动态发送对象列表并创建modal.this应该是json string [{ “city_id”: “1”, “STATE_NAME”: “状态1”},{ “city_id”: “1”, “STATE_NAME”: “22”}]。 对于发送单个对象,我的代码在

下面
NSString *cityId=@"1";
NSString *statNam=@"state1";
NSArray *keys = [NSArray arrayWithObjects:@"city_id",@"state_name",nil];
NSArray *objects = [NSArray arrayWithObjects:cityId,statNam,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];


NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
in NSLog my jsonString is  {"city_id":"1","state_name":"state1"}

1 个答案:

答案 0 :(得分:1)

您需要迭代您的集合对象,将其添加到另一个可变容器中,然后将其作为不可变集合传递给NSJSONSerialization
 我假设您的数据列表yourActualCollect是字典数组。

 NSMutableArray *yourDynamicModelArray = [NSMutableArray array];

    for(int indexNumber = 0; indexNumber < [yourActualCollect count]; indexNumber++){
        NSString *cityId = [[yourActualCollect objectAtIndex:indexNumber] objectForKey@"city_id"];
        NSString *statNam = [[yourActualCollect objectAtIndex:indexNumber] objectForKey@"state_name"];;
        NSArray *keys = [NSArray arrayWithObjects:@"city_id",@"state_name",nil];
        NSArray *objects = [NSArray arrayWithObjects:cityId,statNam,nil];
        NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        [yourDynamicModelArray addObject:jsonDictionary];
    }

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithArray:yourDynamicModelArray] options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);