//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);
其一:字典转json
//字典转Json - (NSString*)dictionaryToJson:(NSDictionary *)dic { NSError *parseError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; }
其二:json转字典
/*! * @brief 把格式化的JSON格式的字符串转换成字典 * @param jsonString JSON格式的字符串 * @return 返回字典 */ + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if(err) { NSLog(@"json解析失败:%@",err); return nil; } return dic; }