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字符串和字典互转的更多相关文章

  1. Json字符串与字典互转

    #pragma mark 转换json字符串 +(NSString *)toJSON:(id)aParam { NSData   *jsonData=[NSJSONSerialization data ...

  2. Swift3 JSON字符串和字典互转(JSON字符串转字典和字典转JSON字符串)

    直接上代码吧 1.JSONString转换为字典 /// JSONString转换为字典 /// /// - Parameter jsonString: <#jsonString descrip ...

  3. iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转

    iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转 1. 字典转Json字符串 // 字典转json字符串方法 -(NSString *)convertToJs ...

  4. [Swift]JSON字符串与字典(Dictionary)、数组(Array)之间的相互转换

    1.JSON字符串与字典(Dictionary)之间的相互转换 import Foundation //JSON字符串转换为字典(Dictionary) func getDictionaryFromJ ...

  5. json字符串和字典的区别补充

    json字符串和字典的区别:json:(JavaScript Object Notation)的首字母缩写,字面的意思是(javascript对象表示法),这里说的json指的是类似于javascri ...

  6. json字符串和dict互转

    json字符串和dict互转 import json str = '{"params":[{"id":222,"offset":0},{&q ...

  7. json字符串和字典类型的相互转换

    在开发过程中,有时候需要将json字符串转为字典类型,反之亦然,通常采用.Net的开源类库Newtonsoft.Json进行序列化,这里我也是采用这个,不过我更喜欢写扩展方法方便在项目的调用. 首先新 ...

  8. json字符串和字典的区别

    json字符串和字典的区别: json: (JavaScript Object Notation)的首字母缩写,字面的意思是(javascript对象表示法),这里说的json指的是类似于javasc ...

  9. Swift开发中 JSON对象/JSON字符串/Data的互转

    本文将介绍Swift开发中常用的转换(JSON对象/JSON字符串/Data之间的互相转换) #pragma mark - JSON(对象)----->JSON字符串 1.原生方法 //JSON ...

随机推荐

  1. python操作redis数据

    一.环境安装 1.redispy安装 (automatic) C:\Users\Administrator>pip install redis 2.检测是否安装成功 (automatic) C: ...

  2. Centos6.5升级安装openssh7.7p1

    Centos6.5升级安装openssh7.7p1  关于OpenSSH漏洞   2016年1月14日OpenSSH发布官方公告称, OpenSSH Client 5.4~7.1 版本中未公开说明的功 ...

  3. leetcode-12周双周赛-5090-抛掷硬币

    题目描述: 二维dp: class Solution: def probabilityOfHeads(self, prob: List[float], target: int) -> float ...

  4. 移动Windows开始按钮到任务栏中的任何位置

    uses CommCtrl; procedure TForm1.Button1Click(Sender: TObject); var vHandle: THandle; vCount: Integer ...

  5. NX二次开发-NXOPEN自动切换到工程图模块

    UFUN的API里是没有切换到工程图的函数的,NXOPEN里是有方法可以用的.不过应该是不支持NX9以下的版本. NX9的不能录制出来,在UI类里有方法 NX9+VS2012 #include < ...

  6. 2018-2019-2-20175323 java实验三敏捷开发与XP实践

    代码规范 安装alibaba插件 首先使用code栏里面的reformat code使代码的格式更加规范 再用编码规约扫描,alibaba把问题分为block/critical/major三个等级,出 ...

  7. (转)Java NIO框架Mina、Netty、Grizzly介绍与对比

    转:http://blog.csdn.net/cankykong1/article/details/19937027 Mina: Mina(Multipurpose Infrastructure fo ...

  8. c++ 实现元组 重载cout os 输出

    #include <iostream> #include <string> using namespace std; class CAnyType //: public COb ...

  9. [转]关于tomcat 中的 tomcat-users.xml 配置不生效原因

    安装完tomcat,或者解压完tomcat后,在tomcat的目录下有个conf文件夹,在这个文件夹下面有一个tomcat- users.xml的文件,这个文件里面的配置信息是当我们进入http:// ...

  10. PAT_A1053#Path of Equal Weight

    Source: PAT A1053 Path of Equal Weight (30 分) Description: Given a non-empty tree with root R, and w ...