美文网首页
json与oc数据互转

json与oc数据互转

作者: Miss_QL | 来源:发表于2018-02-27 10:29 被阅读7次

1、json -> OC
情景:服务器返回带斜杠数据,自己解析。
eg:

 result = "{\"account\":\"13656685594\",\"count\":0,\"gmtCreate\":null,\"gmtModify\":null,\"id\":0,\"staticToken\":\"5f3498854f4ecd284d772d71b0c74a33\",\"token\":\"03ff8978f6eb98150c5adf4e5fd2fc49\"}";

解析步骤:

NSData * data = [dic[@"result"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[[NSUserDefaults standardUserDefaults] setObject:resultDic[@"token"] forKey:@"token"];
[[NSUserDefaults standardUserDefaults] setObject:resultDic[@"staticToken"] forKey:@"staticToken"];

2、OC -> json

NSDictionary * dict = @{@"name":@"xiaoMing", @"age":@20, @"sex":@YES};
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json = %@", json);

相关文章

网友评论

      本文标题:json与oc数据互转

      本文链接:https://www.haomeiwen.com/subject/dxspxftx.html