• 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

    //字典转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;  
    }  
    
  • 相关阅读:
    [Docker] Windows 宿主环境下,共享或上传文件到容器的方法
    [Docker]
    [Docker]
    [Docker]
    [Windows]
    [Linux] 树莓派 4B 安装 Ubuntu 19.10 (Eoan Ermine) IOT 版
    [Linux]
    [.Net] 什么是线程安全的并发集合
    [IOT]
    c++库大全
  • 原文地址:https://www.cnblogs.com/boyuanmeng/p/4370922.html
Copyright © 2020-2023  润新知