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

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

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

...which results in:

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

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

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

推荐答案

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

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相关问答推荐

在Jenkins中使用ReadJSON读取json子元素

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

如何将响应数据保存到Flutter 中的共享首选项中

使用 jq 和脚本 bash 映射两个 json

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

使用带有逗号的字段名称构建 struct

MarkLogic REST 资源 API - 仅使用一个 POST 请求修补多个文档

JSON.NET 中特定对象的自定义转换

Angularjs访问本地json文件

JSON extract\set 的 SQLite JSON1 示例

将错误消息作为 JSON 对象发送

在视图中将 .Net 对象转换为 JSON 对象

Json.NET 是否缓存类型的序列化信息?

JSON Schema:验证数字或空值

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

如何转换为 D3 的 JSON 格式?

从 Json 对象 Android 中获取字符串值

在 iPhone 上解析 JSON 日期

如何从 jQuery ajax 调用将复杂对象传递给 ASP.NET WebApi GET?

使用 JSON.NET 序列化/反序列化对象字典