Swift - 如何将 json 字符串响应解码为字符串?

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)

错误:无法将类型 'String' 的值转换为预期的参数类型 'Data'

在其他语言中,例如 javascript 或 java/kotlin,将此响应转换为字符串非常容易。

JS

const s = JSON.parse(" \"This is a response\" ")

科特林

val s = Gson().fromJson(String::class.java, " \"This is a response\" ")

但在 swift 中,它似乎并不那么简单。此回复是否有效 json?我假设双引号会使它成为一个有效的 json 对象。

提前致谢。

您需要先将 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)