本文介绍了Swift:将结构转换为JSON吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个struct,并希望将其另存为JSON文件.

I created a struct and want to save it as a JSON-file.

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对象转换为类似内容:

But how can I convert the struct object to something like:

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

推荐答案

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

Swift 4 introduces the Codable protocol which provides a very convenient way to encode and decode custom structs.

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) }

这篇关于Swift:将结构转换为JSON吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:09