一尘不染

Swift:将结构转换为JSON吗?

swift

我创建了一个,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"
}

阅读 262

收藏
2020-07-07

共1个答案

一尘不染

您可以添加一个计算属性以获取JSON表示,并添加静态(类)函数以从Sentence数组创建JSON 数组。

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

  static func jsonArray(array : [Sentence]) -> String
  {
    return "[" + array.map {$0.jsonRepresentation}.joinWithSeparator(",") + "]"
  }

  var jsonRepresentation : String {
    return "{\"sentence\":\"\(sentence)\",\"lang\":\"\(lang)\"}"
  }
}


let sentences = [Sentence(sentence: "Hello world", lang: "en"), Sentence(sentence: "Hallo Welt", lang: "de")]
let jsonArray = Sentence.jsonArray(sentences)
print(jsonArray) // [{"sentence":"Hello world","lang":"en"},{"sentence":"Hallo Welt","lang":"de"}]

编辑:

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

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