美文网首页iOS Developer
NSDictionary或者NSArray转换成JSON串

NSDictionary或者NSArray转换成JSON串

作者: 踩坑小分队 | 来源:发表于2017-04-27 09:56 被阅读136次

    简单的记录一下

        NSDictionary *dic1 = @{@"a":@"1"};
        NSDictionary *dic2 = @{@"b":@"2"};
        NSArray *array = @[@"1",@"1",@"1",@"1",@"1",@"1",dic1,dic2];
        NSString *arrayStr = [self transformationToString:array];
        NSLog(@"数组转化后的结果 == \n%@",arrayStr);
        
        
        NSDictionary *tempDic = @{@"name":@"张三",@"age":@(20),@"dic2":dic2};
        NSString *tempDicStr = [self transformationToString:tempDic];
        NSLog(@"字典转化后的结果是 == \n%@",tempDicStr);
    
    /**字典或者数组转化成json串*/
    - (NSString *)transformationToString:(id )transition{
        NSString *jsonString = nil;
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:transition
                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                             error:&error];
        if (! jsonData) {
            NSLog(@"Got an error: %@", error);
            return @"转化失败";
            
        } else {
            
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            return jsonString;
            
        }
    }
    

    转化后的结果是:

    arrayStr == 
    [
      "1",
      "1",
      "1",
      "1",
      "1",
      "1",
      {
        "a" : "1"
      },
      {
        "b" : "2"
      }
    ]
    
    
    {
      "name" : "张三",
      "age" : 20,
      "dic2" : {
        "b" : "2"
      }
    }
    

    相关文章

      网友评论

        本文标题:NSDictionary或者NSArray转换成JSON串

        本文链接:https://www.haomeiwen.com/subject/xrjgzttx.html