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]);
        }
        
    }
  • 相关阅读:
    BufferedOutPutStream 字节缓冲输出流 BufferedIntPutSream 字节缓冲输入流
    Properpies
    jdk9的新特性
    try catch finally处理流的异常
    续写和换行
    write写入
    flush close
    Postman功能详解
    HyLoad压测的使用
    找出Window/Linux下 占用端口的进程
  • 原文地址:https://www.cnblogs.com/fs-ios/p/4995176.html
Copyright © 2011-2022 走看看