iOS開發--字典(NSDictionary)和JSON字符串(NSString)之間互轉

iOS開發--字典(NSDictionary)和JSON字符串(NSString)之間互轉

1. 字典轉Json字符串

// 字典轉json字符串方法html

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

{post

    NSError *error;ui

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

    NSString *jsonString;spa

    if (!jsonData) {code

        NSLog(@"%@",error);htm

    }else{blog

        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:@"\n" 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; }
相關文章
相關標籤/搜索