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 ...
随机推荐
- 从数据库更新模型报错:无法将运行时连接字符串转换为设计时等效项,没有为提供程序“mysql.data.mysqlclient”安装为设计目的启用visual studio以便与数据库进行通信所需要的库
评论里有同学说:VS2017 Enterprise版本的无效,我现在也是用的vs2017Enterprise版本,数据库也是mysql的,但没遇到过.在此说明一下. 一.环境:VS2015 + EF ...
- zeromq protobuf例子
https://github.com/AifiHenryMa/zeromq_protocolbuffer_demo https://github.com/protocolbuffers/protobu ...
- Simple example of use of __setstate__ and __getstate__
class Foo(object): def __init__(self, val=2): self.val = val def __getstate__(self): print ("I' ...
- Jenkins配置gitlab
一.免密公钥登陆1 登陆gitlab 搜ssh Keys 2 添加在Jenkins 服务器本地创建好的公钥 保存完成 也可以手动添加 到/var/opt/gitlab/.ssh/authorized_ ...
- delphi xe10 安卓设备信息
//引用单元 FMX.Android.DeviceInfo.GetInformation; Memo1.Lines.Add('ID:'+FMX.Android.DeviceInfo.ID); Memo ...
- Android中的APK,TASK,PROCESS,USERID之间的关系
开发Android已经有一段时间了,今天接触到底层的东西,所以对于进程,用户的id以及Android中的Task,Apk之间的关系,要做一个研究,下面就是研究结果: apk一般占一个dalvik,一个 ...
- NX二次开发-UFUN获取相邻面UF_MODL_ask_adjac_faces
NX9+VS2012 #include <uf.h> #include <uf_obj.h> #include <uf_modl.h> UF_initialize( ...
- C++从string中删除所有的某个特定字符【转载】
转载自https://www.cnblogs.com/7z7chn/p/6341453.html C++中要从string中删除所有某个特定字符, 可用如下代码 str.erase(std::remo ...
- vue中使用router全局守卫实现页面拦截
一.背景 在vue项目中使用vue-router做页面跳转时,路由的方式有两种,一种是静态路由,另一种是动态路由.而要实现对路由的控制需要使用vuex和router全局守卫进行判断拦截(安全问题文章最 ...
- 数据结构C++版-图
一.概念及分类 二.图的存储结构 1.邻接矩阵 顶点: 弧: 边: 表达式语句: 2.邻接表 逆邻接表: 3.十字链表 4.邻接多重表 三.图的权值概念及遍历 权值: 图的遍历: 1.深度优先搜索 2 ...