JSONSerialization.WritingOptions

介绍 WritingOptions

下面的枚举有 4 个 option,但是有一个是 13beta 版本的,文档也写了 unavilible,所以我们直接跳过,就看可以使用的是 3 个,分别是:

  • prettyPrinted JSON 美化格式带换行,空格等

  • sortedKeys 对 JSON 的 Object 对象的 Key 进行排序

  • fragmentsAllowed 允许所有的 JSON 对象类型作为 JSON 的根类型

分别是什么意思

    @available(iOS 5.0, *)
    public struct WritingOptions : OptionSet {

        public init(rawValue: UInt)


        public static var prettyPrinted: JSONSerialization.WritingOptions { get }


        /* Sorts dictionary keys for output using [NSLocale systemLocale]. Keys are compared using NSNumericSearch. The specific sorting method used is subject to change.
         */
        @available(iOS 11.0, *)
        public static var sortedKeys: JSONSerialization.WritingOptions { get }

        public static var fragmentsAllowed: JSONSerialization.WritingOptions { get }

        @available(iOS 13.0, *)
        public static var withoutEscapingSlashes: JSONSerialization.WritingOptions { get }
    }

验证

零,none

let json: [String: Any] = ["name": "xiaoxin", "address": ["province":"test", "city":"test"], "c":["c":"123","a":"321"]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
  let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)
  print(jsonString!)

} catch {
  print(error)
}
// 输出
{"c":{"c":"123","a":"321"},"name":"xiaoxin","address":{"province":"test","city":"test"}}

一,prettyPrinted

let json: [String: Any] = ["name": "xiaoxin", "address": ["province":"test", "city":"test"], "c":["c":"123","a":"321"]]
do {
  let jsonData = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted])
  let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)
  print(jsonString!) 
} catch {
  print(error)
}
// 输出
{
  "address" : {
    "province" : "test",
    "city" : "test"
  },
  "name" : "xiaoxin",
  "c" : {
    "c" : "123",
    "a" : "321"
  }
}

二,sortedKeys

可以看到 排序是递归的,这个 JSON 所有的 Object 的 Key 都被排序了。 不管是外层还是内层。

let json: [String: Any] = ["name": "xiaoxin", "address": ["province":"test", "city":"test"], "c":["c":"123","a":"321"]]
do {
    let jsonData = try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys,.prettyPrinted])
  let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)
  print(jsonString!)

} catch {
  print(error)
}
// 输出
{
  "address" : {
    "city" : "test",
    "province" : "test"
  },
  "c" : {
    "a" : "321",
    "c" : "123"
  },
  "name" : "xiaoxin"
}

三,fragmentsAllowed

允许所有 JSON 所有的类型,作为 JSON 的最外层。 比如,一个 Number,String,Bool,Null 都可以作为一个 JSON,没有带上这个 option,默认只允许,Object 和 Arrary 这两种类型作 JSON 的最外层。

let json = 13840150344
do {
    let jsonData = try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys,.prettyPrinted])
  let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)
  print(jsonString!)

} catch {
  print(error)
}
//输出
13840150344

最后更新于