码迷,mamicode.com
首页 > 其他好文 > 详细

NSData 转换 Dictionary

时间:2015-01-15 18:02:52      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

#import "NSDataToDictionaryTools.h"

@implementation NSDataToDictionaryTools


+(NSData *)NSDictionaryToNSData:(NSDictionary *)dictionary
{
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:dictionary forKey:@"KeyValue"];
    [archiver finishEncoding];
    
    return data;
}


+(NSString *)NSDictionaryToJSON:(NSDictionary *)dictionary
{

    NSData *prettyJson = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonstr = [self NSDataToNSString:prettyJson];
    return  jsonstr;
}


+(NSDictionary *)NSDataToNSDictionary:(NSData *)data
{
    //NSData-->NSDictionary
    NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    //NSData-->NSDictionary
//    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//    NSDictionary *myDictionary = [unarchiver decodeObjectForKey:@"KeyValue"];
//    [unarchiver finishDecoding];
    
    return myDictionary;
}


//NSString和NSData转换(即可作json串互相转换)
+(NSString *)NSDataToNSString:(NSData *)data
{
    //NSData-> NSString
    NSString *myString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return myString;
    
    //NSString->NSData
    //NSString *aString = @"我是NSString";
    //NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
}


@end

 

NSData 转换 Dictionary

标签:

原文地址:http://www.cnblogs.com/allanliu/p/4226596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!