I want to make one function in my swift project that converts String to Dictionary json format but I got one error:
Cannot convert expression\'s type
for swift 5, I write a demo to verify it.
extension String {
/// convert JsonString to Dictionary
func convertJsonStringToDictionary() -> [String: Any]? {
if let data = data(using: .utf8) {
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any]
}
return nil
}
}
let str = "{\"name\":\"zgpeace\"}"
let dict = str.convertJsonStringToDictionary()
print("string > \(str)")
// string > {"name":"zgpeace"}
print("dicionary > \(String(describing: dict))")
// dicionary > Optional(["name": zgpeace])