iOS开发JSON字符串和字典互转
1、相关属性简述
NSJSONReadingOptions读取属性:
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
NSJSONReadingMutableContainers = (1UL << ),// 返回可变容器
NSJSONReadingMutableLeaves = (1UL << ), // 不仅返回的最外层是可变的, 内部的子数值或字典也是可变对象
NSJSONReadingAllowFragments = (1UL << )// 返回允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON格式
} API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
NSJSONWritingOptions写入属性:
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
NSJSONWritingPrettyPrinted = (1UL << ),//是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
NSJSONWritingSortedKeys API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) = (1UL << )//输出的json字符串就是一整行 ios11.0之后
} API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
2、字典转JSON字符串
不论转JSON字符串,还是转回字典,都需要通过NSData这个桥梁!
2.1、如果NSJSONWritingOptions枚举为NSJSONWritingPrettyPrinted:
NSJSONWritingPrettyPrinted = (1UL << ),//是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
- (NSString *)jsonStringOriWithDict:(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;
}
NSJSONWritingPrettyPrinted代码
打印结果:很美观
但是此时的JSON字符串有空格和 \n ,是这个样子:
2.2、在之前基础上进行去空格和区 \n 操作,就能到达我们想要的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];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的换行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
return mutStr;
}
NSJSONWritingPrettyPrinted去空格和\n
打印结果:就是一行
JSON字符串:
2.3、 在ios11.0之后推出新的枚举值:NSJSONWritingSortedKeys一次就可以解决空格和\n问题:
- (NSString *)jsonStringWithDict2:(NSDictionary *)dict{
NSError *error;
NSString *jsonString;
if (@available(iOS 11.0, *)) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingSortedKeys error:&error];
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
} else {
jsonString = [self jsonStringWithDict:dict];
}
return jsonString;
}
NSJSONWritingSortedKeys代码
打印结果:也是一行
JSON字符串:
3、JSON字符串转字典
没什么可说的的,老代码一份:
- (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;
}
iOS开发JSON字符串和字典互转的更多相关文章
- Json字符串与字典互转
#pragma mark 转换json字符串 +(NSString *)toJSON:(id)aParam { NSData *jsonData=[NSJSONSerialization data ...
- Swift3 JSON字符串和字典互转(JSON字符串转字典和字典转JSON字符串)
直接上代码吧 1.JSONString转换为字典 /// JSONString转换为字典 /// /// - Parameter jsonString: <#jsonString descrip ...
- iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转
iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转 1. 字典转Json字符串 // 字典转json字符串方法 -(NSString *)convertToJs ...
- [Swift]JSON字符串与字典(Dictionary)、数组(Array)之间的相互转换
1.JSON字符串与字典(Dictionary)之间的相互转换 import Foundation //JSON字符串转换为字典(Dictionary) func getDictionaryFromJ ...
- json字符串和字典的区别补充
json字符串和字典的区别:json:(JavaScript Object Notation)的首字母缩写,字面的意思是(javascript对象表示法),这里说的json指的是类似于javascri ...
- json字符串和dict互转
json字符串和dict互转 import json str = '{"params":[{"id":222,"offset":0},{&q ...
- json字符串和字典类型的相互转换
在开发过程中,有时候需要将json字符串转为字典类型,反之亦然,通常采用.Net的开源类库Newtonsoft.Json进行序列化,这里我也是采用这个,不过我更喜欢写扩展方法方便在项目的调用. 首先新 ...
- json字符串和字典的区别
json字符串和字典的区别: json: (JavaScript Object Notation)的首字母缩写,字面的意思是(javascript对象表示法),这里说的json指的是类似于javasc ...
- Swift开发中 JSON对象/JSON字符串/Data的互转
本文将介绍Swift开发中常用的转换(JSON对象/JSON字符串/Data之间的互相转换) #pragma mark - JSON(对象)----->JSON字符串 1.原生方法 //JSON ...
随机推荐
- php array remove empty values
print_r(array_filter($linksArray)); 參考 Remove empty array elements Remove Empty Array Elements In PH ...
- 关于mybaitis
mybatis启动流程 1.首先来看看最简单的mybatis项目启动过程 public static void mybatisTest() throws IOException { String re ...
- thinkphp 缓存驱动
缓存驱动默认位于Think\Cache\Driver命名空间下面,目前已经提供了包括APC.Db.Memcache.Shmop.Sqlite.Redis.Eaccelerator和Xcache缓存方式 ...
- 显示所有用户,mysql的基本操作
可以实现显示数据库中所有用户. select user from mysql.user; select user,host,password from mysql.user; 给表创建用户,授权: ...
- NX二次开发-UFUN选择草图对话框UF_UI_select_sketch
#include <uf.h> #include <uf_ui.h> UF_initialize(); //选择草图对话框 char sMessage[] = "选择 ...
- webconfig节点值里的文字换行问题
有时候会遇到在配置节点中配置文字的问题,比如: <add key="notice" value="温馨提示:1,感谢您访问; \n 2,谢谢来访"/> ...
- iOS报错锦集
1.Your session has expired. Please log in. 提示“Your session has expired. Please log in.” 解决办法: Xcode ...
- jQuery 表单域选中选择器
复选框.单选按钮.下拉列表 /***********************************************/ <script type="text/javascrip ...
- chomp
用来除去最后的换行等空白字符. 例程: #!/usr/bin/perl #chomp.pl use warnings; use strict; print "Input a string & ...
- CodeForces-1215C-Swap Letters-思维
Monocarp has got two strings ss and tt having equal length. Both strings consist of lowercase Latin ...