zoukankan      html  css  js  c++  java
  • 字典、数组、JSON之间的转化小demo

    /**
     *  数组转JSON.
     */
    - (void)testJsonAndArray
    {
        NSArray *arr = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f", nil];
        
        NSLog(@"arrar = %@",arr);
        
        NSError *error = nil;
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:&error];
        
        if (!error)
        {
            NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            NSLog(@"json = %@",json);
        }
    }
    /**
     *  测试json和对象、字典转json
     */
    - (void)testJsonAndDict
    {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"张三",@"name",
                              @"20",@"age",@"180",@"height", nil];
        
        NSLog(@"DIC = %@",dict);
        
        NSError *error = nil;
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        if (error == nil)
        {
            NSLog(@"字典转JSON成功,JSON = %@",json);
        }
        
    }
    /**
     *  把JSON转换成object对象,可能是字典、可能是数组。
     *
     *  @param json 传进来的 json 字符串
     */
    - (void)JsonToObjectWithJosn:(NSString *)json
    {
        
    //    JSON  用来在网络上进行数据传输的一种数据格式。是一种特殊的字符串。
        
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        
        NSError *error = nil;
        
        id result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        
        if (error == nil)
        {
            NSLog(@"%@ -- %@",result,[result class]);
        }
        
    }
  • 相关阅读:
    MYSQL数据库基于MHA的高可用
    2019.9.20 Tomcat部署SL商城系统并连接MariaDB数据库
    2019.9.20 nginx+tomcat的负载均衡集群
    2019.9.20 tomcat自定义网站测试
    2019.9.20 Tomcat 安装和jdk的解压
    2019.9.19 tomcat 虚拟主机
    2019.9.19 tomcat配置ssl加密
    2019.9.18 nfs共享与动静分离
    2019.9.17 用户访问网站过程
    2019.9.17 awk上课总结
  • 原文地址:https://www.cnblogs.com/fs-ios/p/4995176.html
Copyright © 2011-2022 走看看