iOS常用方法——NSArray、NSDictionary与json的相互转换

开发中常用到NSArray、NSDictionary转换为json格式和json解析为NSArray、NSDictionary。不多说,直接上干货。

  • NSArray、NSDictionary转换为json:
+(NSString *)objectToJson:(id)obj{
    if (obj == nil) {
        return nil;
    }
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj
                                                       options:0
                                                         error:&error];

    if ([jsonData length] && error == nil){
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        return nil;
    }
}

该方法可以写在NSString的分类中,直接用NSString调用,很方便。

  • json转NSArray、NSDictionary:
+(id)jsonToObject:(NSString *)json{
    //string转data
    NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    //json解析
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return obj;
}

该方法可以写在一个公用类,也可以与上面的方法放在一起,虽然返回的不是NSString类型,但是功能互逆也是有关联的,放在一起也无可厚非。

  • 调用示例代码:
#import "ViewController.h"
#import "NSString+Json.h"

@interface ViewController ()

@end

@implementation ViewController

 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    NSArray * array = @[@"张三",@"李四",@"三年级",@"hello",@"world"];
    NSString * arrayJson = [NSString objectToJson:array];
    NSLog(@"array === %@",array);
    NSLog(@"array to json === %@",arrayJson);
    NSLog(@"json to array == %@",[NSString jsonToObject:arrayJson]);

    NSDictionary * dic = @{@"姓名":@"Lily",@"年龄":@10,@"班级":@2,@"座右铭":@"好好学习,天天向上!"};
    NSString * dicJson = [NSString objectToJson:dic];
    NSLog(@"dictionary === %@",dic);
    NSLog(@"dictionary to json === %@",dicJson);
    NSLog(@"json to dictionary == %@",[NSString jsonToObject:dicJson]);
}
  • 打印结果:
array === (
    "\U5f20\U4e09",
    "\U674e\U56db",
    "\U4e09\U5e74\U7ea7",
    hello,
    world
)
array to json === ["张三","李四","三年级","hello","world"]
json to array == (
    "\U5f20\U4e09",
    "\U674e\U56db",
    "\U4e09\U5e74\U7ea7",
    hello,
    world
)
dictionary === {
    "\U59d3\U540d" = Lily;
    "\U5e74\U9f84" = 10;
    "\U5ea7\U53f3\U94ed" = "\U597d\U597d\U5b66\U4e60\Uff0c\U5929\U5929\U5411\U4e0a\Uff01";
    "\U73ed\U7ea7" = 2;
}
dictionary to json === {"姓名":"Lily","座右铭":"好好学习,天天向上!","班级":2,"年龄":10}
json to dictionary == {
    "\U59d3\U540d" = Lily;
    "\U5e74\U9f84" = 10;
    "\U5ea7\U53f3\U94ed" = "\U597d\U597d\U5b66\U4e60\Uff0c\U5929\U5929\U5411\U4e0a\Uff01";
    "\U73ed\U7ea7" = 2;
}

猜你喜欢

转载自blog.csdn.net/aaaaazq/article/details/80760646