ios的对象数组生成jsonarray

//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
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


你可能感兴趣的:(ios的对象数组生成jsonarray)