zoukankan      html  css  js  c++  java
  • NSData 转换 Dictionary

    #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
  • 相关阅读:
    TypeError: Buffer.alloc is not a function
    node.js服务端程序在Linux上持久运行
    C#中的反射
    群要事日记
    vs2017 自定义生成规则 错误 MSB3721 命令 ”已退出,返回代码为 1。
    VP9 Video Codec
    用户手册是Yasm汇编
    更改Mysql数据库存储位置
    注册表项
    C#开发可以可视化操作的windows服务
  • 原文地址:https://www.cnblogs.com/allanliu/p/4226596.html
Copyright © 2011-2022 走看看