有个需求需要把字典转成Json字符串,但是Json字符串Key值,按照ASCII码排序
一、系统自带JSONString方式,无法做到排序
let data :NSData! =try? JSONSerialization.data(withJSONObject: dictionary, options: [])asNSData!
let JSONString = NSString(data:dataasData,encoding: String.Encoding.utf8.rawValue)
return JSONString!asString
二、iOS11 开始支持排序参数传入
if #available(iOS 11.0, *) {
let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions.sortedKeys) as NSData!
let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
return JSONString! as String
}
WritingOptions中包含排序
三、为了适配各种版本,自定义拼接
func creatJsonString(dict: [String:Any]) ->String{
if(!JSONSerialization.isValidJSONObject(dict)) {
print("无法解析出JSONString")
return""
}
var namedPaird = [String]()
let sortedKeysAndValues = dict.sorted{$0.0< $1.0}
for(key, value) in sortedKeysAndValues {
if value is [String:Any] {
namedPaird.append("\"\(key)\":\(self.creatJsonString(dict: valueas! [String:Any]))")
}else if value is [Any] {
namedPaird.append("\"\(key)\":\(value)")
}else{
namedPaird.append("\"\(key)\":\"\(value)\"")
}
}
let returnString = namedPaird.joined(separator:",")
return"{\(returnString)}"
}