工作中遇到要给服务器传递相对复杂的数据类型:字典里嵌套数组,字典里多层嵌套字典这种情况.如果单纯的把Model转化为字典然后进行上传,服务器那边根本接收不到.所以就要把要上传的复杂结构类型转换为字符串,这里简单举个例子.
1.数组中的数据拼接:
要传递的数据:
[{“user”:”王思聪”,”certType”:”0”,”certNo”:”5224245698653256”,”userType”:”1”},{“user”:”王小妹”,”certType”:”0”,”certNo”:”5224245698756256”,”userType”:”1”}]拼接方法:
NSArray *passenger = dic[@”passenger”];
NSMutableString *passengerStr = [[NSMutableString alloc] init];
for(int i=0;i<passenger.count;i++){
NSDictionary *model = passenger[i];
NSString *str = [NSString stringWithFormat:@"{certNo:\"%@\",certType:\"%@\",user:\"%@\",userType:\"%@\"}",model[@"certNo"],model[@"certType"],model[@"user"],model[@"userType"]];
if (i==0) {
passengerStr = [NSMutableString stringWithString:[NSString stringWithFormat:@"%@%@",passengerStr,str]];
}else{
passengerStr = [NSMutableString stringWithString:[NSString stringWithFormat:@"%@,%@",passengerStr,str]];
}
}
NSString *str2 = [NSString stringWithFormat:@"[%@]",passengerStr];
[dic setValue:str2 forKey:@"passenger"];
2.字典里边的字典嵌套
要传递的数据:
voucher:{
voiceSign:发票抬头,
nsrsbh:企业税号,
address:寄送地址
}
拼接方法: NSString *voucherStr = [NSString stringWithFormat:@”{:\”%@\”,nsrsbh:\”%@\”,address:\”%@\”}”,voucher[@”voiceSign”],voucher[@”nsrsbh”],voucher[@”address”]];
[dic setValue:voucherStr forKey:@”voucher”];