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 ...
随机推荐
- 【学术篇】51nod 1238 最小公倍数之和
这是一道杜教筛的入(du)门(liu)题目... 题目大意 求 \[ \sum_{i=1}^n\sum_{j=1}^nlcm(i,j) \] 一看就是辣鸡反演一类的题目, 那就化式子呗.. \[ \s ...
- Burnside引理&Pólya定理
Burnside's lemma 引例 题目描述 一个由2*2方格组成的正方形,每个格子上可以涂色或不涂色, 问共有多少种本质不同的涂色方案. (若两种方案可通过旋转互相得到,称作本质相同的方案) 解 ...
- Mybatis枚举转换
自定义mybatis枚举转换,原理是如果用户没有定义自己的枚举转换工具,mybatis在解析枚举类时会自动获取mybatis的BaseTypeHandler,来转换枚举类,我们只需要重写这个枚举转换器 ...
- 请问在一个固定div大小里面,图片右移动,超出div容器的图片给隐藏,怎么设定?
如图,让图片移动,溢出的图片被隐藏,怎么设置? overflow: hidden;
- 清除浏览器默认样式——css reset & normalize.css
css reset 自己挨个清除很麻烦 可以使用网上一些css库——css reset 把模板复制到css文件最上方,其他的样式我们自己编写来覆盖它们 但是这个也有一些弊端,会把一些本来需要的样式给清 ...
- curl命令,curl实现post,curl监控网页shell脚本,curl多进程实现并控制进程数,
cURL > Docs > Tutorial: http://curl.haxx.se/docs/httpscripting.html 下载单个文件,默认将输出打印到标准输出中(STDO ...
- 安装JDK9之后eclipse无法启动问题解决办法
操作系统:MAC OS JDK:1.8.0_131 eclipse:官网最新版 安装jdk的过程很简单,从官网下载之后依次点击就可以了,在终端输入:java -version 可以看到安装后的版本信息 ...
- [转] 多个文件目录下Makefile的写法
1.前言 目前从事于linux下程序开发,涉及到多个文件,多个目录,这时候编译文件的任务量比较大,需要写Makefile.关于Makefile的详细内容可以参考网上流传非常广泛的<跟我一起写Ma ...
- IAsyncResult
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- (转)python常用模块(模块和包的解释,time模块,sys模块,random模块,os模块,json和pickle序列化模块)
阅读目录 1.1.1导入模块 1.1.2__name__ 1.1模块 什么是模块: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代 ...