复制 @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 }
}
复制 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" }}
复制 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"
}
}
复制 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"
}
允许所有 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