Swift 字典转换为JSONString JSONString转换为字典
发布网友
发布时间:2023-03-13 20:16
我来回答
共1个回答
热心网友
时间:2023-10-21 16:13
1、JSONString转换为字典
/// JSONString转换为字典
////// - Parameter jsonString: <#jsonString description#>/// - Returns: <#return value description#>func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
let jsonData:Data = jsonString.data(using: .utf8)! let dict =try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
ifdict != nil {
returndictas! NSDictionary
}
return NSDictionary()
}
2、字典转换为JSONString
/**
字典转换为JSONString
- parameter dictionary: 字典参数
- returns: JSONString
*/func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
if(!JSONSerialization.isValidJSONObject(dictionary)) {
print("无法解析出JSONString")
return"" }
let data : NSData! =try? JSONSerialization.data(withJSONObject: dictionary, options: [])asNSData! let JSONString = NSString(data:dataas Data,encoding: String.Encoding.utf8.rawValue)
returnJSONString!asString
}