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]);
        }
        
    }
  • 相关阅读:
    How to configure security of ActiveMQ ?
    CentOS 搭建 nginx + tomcat
    25个 Git 进阶技巧
    写给Git初学者的7个建议
    my links
    Shell scripts to Create a local dir base on the time.
    81For全栈技术网
    一款可视化的在线制作H5
    在线制作h5
    在线制作h5——上帝的礼物
  • 原文地址:https://www.cnblogs.com/fs-ios/p/4995176.html
Copyright © 2011-2022 走看看