Swift:将结构转换为 JSON? [英] Swift: Convert struct to JSON?

查看:58
本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆