gpt4 book ai didi

json - 快速查看 JSONEncode() 输出的优雅方式

转载 作者:搜寻专家 更新时间:2023-10-31 08:19:44 25 4
gpt4 key购买 nike

var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
let json = try? encoder.encode(test)

如何查看 json 的输出?

如果我使用print(json),我唯一得到的是Optional(45 bytes)

最佳答案

encode() 方法返回包含 UTF-8 编码的 JSON 表示的 Data。所以你可以把它转换回一个字符串:

var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
if let json = try? encoder.encode(test) {
print(String(data: json, encoding: .utf8)!)
}

输出:

{"title":"title","description":"description"}

关于json - 快速查看 JSONEncode() 输出的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45019363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com