zoukankan      html  css  js  c++  java
  • iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转

    1. 字典转Json字符串

    // 字典转json字符串方法

    -(NSString *)convertToJsonData:(NSDictionary *)dict

    {

        NSError *error;

        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

        NSString *jsonString;

        if (!jsonData) {

            NSLog(@"%@",error);

        }else{

            jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

        }

        NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

        NSRange range = {0,jsonString.length};

        //去掉字符串中的空格

        [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

        NSRange range2 = {0,mutStr.length};

        //去掉字符串中的换行符

        [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range2];

        return mutStr;

    }

    2. JSON字符串转化为字典

    + (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;
    }
  • 相关阅读:
    sdnu 1513 字符串翻转
    hdu-1559 最大子矩阵(二维树状数组模板题)
    hdu-1556 树状数组
    1049.饭盒
    1092.校门外的树
    1012.区间合并
    1054.数独
    1175.开心的金明 01背包
    空格(Space)的ASCII码值是:32
    js为lable和div赋值
  • 原文地址:https://www.cnblogs.com/ming1025/p/6186171.html
Copyright © 2011-2022 走看看