如果它的单个对象能够发送但如何使用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"}
答案 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);