[英]Swift - How can I decode json string response into a String?
为什么这不起作用?
let jsonResponse = " \"This is a response\" "
let str = try! JSONDecoder().decode(String.self, from: jsonResponse)
print(str)
错误:无法将“字符串”类型的值转换为预期的参数类型“数据”
在其他语言中,例如 javascript 或 java/kotlin,将此响应转换为字符串非常容易。
JS
const s = JSON.parse(" \"This is a response\" ")
Kotlin
val s = Gson().fromJson(String::class.java, " \"This is a response\" ")
但是在 swift 中,这似乎并不简单。 此响应是否有效 json? 我假设双引号会使其成为有效的 json object。
提前致谢。
您需要先将String
转换为Data
以使用JSONDecoder
对其进行解码:
let jsonResponse = " \"This is a response\" "
let data = Data(jsonResponse.utf8)
let str = try! JSONDecoder().decode(String.self, from: data)
print(str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.