NSJSONSerliazition文档翻译和使用
2017-03-24 16:46
253 查看
JSONSerialization文档
文档链接:JSONSerialization类描述:
你用这个类去解析JSON为基本对象,或者将基本对象转化为JSON一个需要被解析为JSON数据的对子昂必须具有一下几个特点:
1. 最顶层对象为NSArray或者NSDictionary。
2. 所有对象应该是NSStrng.NSNumber,NSArray,NSDictionary,或者NSNull的实例。
其他规则可能适用。调用isValidJSONObject(_:)或尝试转换的方法来判断一个给定的对象可以转换为JSON数据
注意:线程安全!
在iOS7及之后或者macOS10.9及之后NSJSONSerliazition是线程安全的。
内嵌类型
JSONSerialization.WritingOptions
Options for writing JSON data.//写JSON数据的方式
JSONSerialization.ReadingOptions
Options used when creating Foundation objects from JSON data//读JSON数据为基本对象的方式—see
jsonObject(with:options:)and
jsonObject(with:options:).
解析JSON数据为基本类型(Swift)
1.通过含json data 的数据解析。//参数:data:含JSON的数据
//参数:JSONSerialization.ReadinOptions 有三种类型mutableContainers(返回数组或者字典可变对象 )mutableLeave(返回可变数组) allowfragment(允许最顶层不是NSArray和NSDcitionary)
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
2.通过InputStream 解析(常常用于网络请求的解析)
//参数:InputStream 输入流
class func jsonObject(with: InputStream, options: JSONSerialization.ReadingOptions = []) throws -> Any
返回值:一个基本对象,如果解析失败则返回nil。
将基本对象转化为JSON数据
1.通过基本对象转为为JSON数据//option参数只有:prettyPrinted
class func data(withJSONObject: Any, options: JSONSerialization.WritingOptions = [])-> Data
返回值:返回json数据(Data/NSData),失败则返回nil;结果数据是使用UTF-8编码
2.通过输出流转化为JSON数据
class func writeJSONObject(Any, to: OutputStream, options: JSONSerialization.WritingOptions = [], error: NSErrorPointer)->Int
返回值:写入流中的字节多少(Int),如果发生错误返回0;
检查是否该对象可以转化为JSON数据返回BOOL
class func isValidJSONObject(Any)->BOOL
NSJSONSerialisation的使用
使用JSONSerialisation可以将网路请求返回的json解析为基本对象,反之,也可以将上传数据序列化为json数据(NSData)上传。可以在字典与数组中轻松转化。
//解析json数据(NSData为网络请求数据)转化为字典。
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//将对象转为json数据
NSData *jsonData = [NSJSONSerialization data WithJSONObject:info options:0 error:nil];
相关文章推荐
- NHibernate文档翻译 第9章----使用AttributesNHibernate.Mapping.Attributes
- Mako 模板系统文档翻译(1) 使用基础
- NHibernate文档翻译---使用AttributesNHibernate.Mapping.Attributes
- FMDB官方使用文档-GCD的使用-提高性能(翻译)
- Cocos2d-x——CocosBuilder官方帮助文档翻译1 使用自定义类
- JConfig帮助文档翻译-在文件系统下的使用
- 中文翻译:pjsip文档(四)之ICE Session的使用方法
- Sencha Touch 2 官方文档翻译之 Using Views in your Applications(使用视图)
- Hierarchy Viewer之官方文档翻译之中英对照之未完不续版之使用详解.
- FMDB官方使用文档-GCD的使用-提高性能(翻译)
- [翻译]使用c#读取word文档
- 微软文档翻译:【最佳实践】使用sharepoint对象模型编程时候的常见问题
- 打算翻译机器学习工具包--SHOGUN使用文档
- Sencha Touch 2 官方文档翻译之 Using Models(使用数据模型)
- Struts2-json-plugin 的使用(翻译自官方文档)
- Mako 模板系统文档翻译(1) 使用基础
- RUBY常用类库文档翻译以及使用示例
- Sencha Touch 2 官方文档翻译之 Using Views in your Applications(使用视图)
- SQLite数据库使用笔记与文档翻译草稿
- FMDB官方使用文档 G-C-D的使用 提高性能(翻译)