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的权限的问题
昨天因为同学的mysql数据库不知道做了什么操作,从而导致root用户无法使用了 具体是使用root用户不需要密码 进去只能看 看到 infomation_schema 表 ,感觉root权限丢失了 ...
- 影响RAKsmart服务器稳定性的相关因素
RAKsmart美国服务器近年来凭借着成熟的技术和性价比吸引着广大站长,那RAKsmart服务器稳定性怎么样呢?有什么影响因素呢?下面来了解一下吧. 因素一:服务器配置 服务器能正常运营是建立在服务器 ...
- leetcood学习笔记-107-二叉树的层次遍历二
题目描述: 方法一: class Solution(object): def levelOrderBottom(self, root): """ :type root: ...
- Elasticsearch集群状态查看命令
_cat $ curl localhost:9200/_cat=^.^=/_cat/allocation/_cat/shards/_cat/shards/{index}/_cat/master/_ca ...
- IAsyncResult
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- BOM DOM 简介
BOM和DOM简介 BOM,Browser Object Model ,浏览器对象模型. BOM主要提供了访问和操作浏览器各组件的方式. 浏览器组件: window(浏览器窗口) locati ...
- (转)元类metaclass
阅读目录 一 前言 二 什么是元类 三 class关键字创建类的流程分析 五 自定义元类控制类OldboyTeacher的创建 六 自定义元类控制类OldboyTeacher的调用 六 再看属性查找 ...
- 实现solr热词排行榜
现在有业务场景,要求实现词库里面,最新,最热的词并显示,点击热词后可以进入相关信息的文章或者句子 热词的显示频率12小时更新一次. 实现思路: 实现步骤:
- python学习6—数据类型之集合与字符串格式化
python学习6—数据类型之集合与字符串格式化 1. 使用id()可以查看一个变量的内存地址: name = 'alex' id(name) 2. 进制转换 十进制转换为二进制等: a = 10 # ...
- <后端>Flask框架
1.Flask框架安装 简介:轻量级WEB框架,类似于简单版本的Django pip install flask 环境文件生成 pip freeze > requirement.txt 环境文件 ...