内容
- 字典转字符串 Dictionary To String
- 字符串转字典 String To Dictionary
字典转字符串 Dictionary To String
工具类:
// MARK: 字典转字符串
func dicValueString(_ dic:[String : Any]) -> String?{
let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
let str = String(data: data!, encoding: String.Encoding.utf8)
return str
}
或者做成扩展:
// MARK: 字典转字符串
extension Dictionary {
func toJsonString() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self,
options: []) else {
return nil
}
guard let str = String(data: data, encoding: .utf8) else {
return nil
}
return str
}
}
字符串转字典 String To Dictionary
工具类
// MARK: 字符串转字典
func stringValueDic(_ str: String) -> [String : Any]?{
let data = str.data(using: String.Encoding.utf8)
if let dict = try? JSONSerialization.jsonObject(with: data!,
options: .mutableContainers) as? [String : Any] {
return dict
}
return nil
}
或者做成扩展
// MARK: 字符串转字典
extension String {
func toDictionary() -> [String : Any] {
var result = [String : Any]()
guard !self.isEmpty else { return result }
guard let dataSelf = self.data(using: .utf8) else {
return result
}
if let dic = try? JSONSerialization.jsonObject(with: dataSelf,
options: .mutableContainers) as? [String : Any] {
result = dic
}
return result
}
}