IOS基础入门OC语言Xcode Day12笔记:Json字符串和字典互转
程序员文章站
2022-03-11 15:24:56
1、Json字符串转字典(1)方法一+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{ if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *d...
1、Json字符串转字典
(1)方法一
+ (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;
}
(2)方法二
-(NSData *)convertToJsonData:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
return jsonData;
}
2、字典转Json字符串
+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
本文地址:https://blog.csdn.net/wenyu_Saitama/article/details/107480989
上一篇: GIS+BIM智慧数字社区- 5G+物联网数字驾驶舱平台
下一篇: Firebase接入