gpt4 book ai didi

json - Swift:将结构转换为 JSON?

转载 作者:IT王子 更新时间:2023-10-29 05:24:50 26 4
gpt4 key购买 nike

我创建了一个 struct 并想将其保存为 JSON 文件。

struct Sentence {
var sentence = ""
var lang = ""
}

var s = Sentence()
s.sentence = "Hello world"
s.lang = "en"
print(s)

...结果是:

Sentence(sentence: "Hello world", lang: "en")

但是我怎样才能将 struct 对象转换成类似这样的东西:

{
"sentence": "Hello world",
"lang": "en"
}

最佳答案

Swift 4 引入了 Codable 协议(protocol),它提供了一种非常方便的方式来编码和解码自定义结构。

struct Sentence : Codable {
let sentence : String
let lang : String
}

let sentences = [Sentence(sentence: "Hello world", lang: "en"),
Sentence(sentence: "Hallo Welt", lang: "de")]

do {
let jsonData = try JSONEncoder().encode(sentences)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString) // [{"sentence":"Hello world","lang":"en"},{"sentence":"Hallo Welt","lang":"de"}]

// and decode it back
let decodedSentences = try JSONDecoder().decode([Sentence].self, from: jsonData)
print(decodedSentences)
} catch { print(error) }

关于json - Swift:将结构转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33186051/

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