//1.创建可变字符串,初始化为数组开头括号
NSMutableString *OptionResult = [[NSMutableString alloc] initWithString:@"["];
//2.for循环拼接字符串
for (int i = 0; i < self.modelArray.count; i ++) {
GreenVoteTableViewCellModel *cellModel = [self.modelArray objectAtIndex:i];
if (cellModel.CStarScore == 1000) {
TTAlert([NSString stringWithFormat:@"请选择第%d题星星",cellModel.VoteThemeID]);
return;
}
if (cellModel.CVoteOptionID == 1000) {
TTAlert([NSString stringWithFormat:@"第%d题单选不能为空",cellModel.VoteThemeID]);
return;
}
NSString *string;
if ([cellModel.Comment isEqualToString:@""]) {
string = [NSString stringWithFormat:@"{\"VoteThemeID\":%d,\"VoteOptionID\":%d,\"StarScore\":%d},",cellModel.VoteThemeID,cellModel.CVoteOptionID,cellModel.CStarScore];
} else {
string = [NSString stringWithFormat:@"{\"VoteThemeID\":%d,\"VoteOptionID\":%d,\"StarScore\":%d,\"Comment\":\"%@\"},",cellModel.VoteThemeID,cellModel.CVoteOptionID,cellModel.CStarScore,cellModel.Comment];
}
[OptionResult appendString:string];
}
// 3. 获取末尾逗号所在位置
NSUInteger location = [OptionResult length]-1;
NSRange range = NSMakeRange(location, 1);
// 4. 将末尾逗号换成结束的]}
[OptionResult replaceCharactersInRange:range withString:@"]"];
//1. 初始化可变字符串,存放最终生成json字串
NSMutableString *jsonString = [[NSMutableString alloc] initWithString:@"{\"actorhalls\":["];
for(ExecplanActosHall *hall in actorhalls){
//2. 遍历数组,取出键值对并按json格式存放
NSString *string;
string = [NSString stringWithFormat:
@"{\"ownerName\":\"%@\",\"ownerId\":\"%@\",\"channelId\":\"%@\",\"ownerType\":\"%ld\"},",hall.ownerName,hall.ownerId,hall.channelId,(long)hall.ownerType];
[jsonString appendString:string];
}
// 3. 获取末尾逗号所在位置
NSUInteger location = [jsonString length]-1;
NSRange range = NSMakeRange(location, 1);
// 4. 将末尾逗号换成结束的]}
[jsonString replaceCharactersInRange:range withString:@"]}"];
NSLog(@"jsonString = %@",jsonString);