Swift:将结构转换为JSON吗? [英] Swift: Convert struct to JSON?
本文介绍了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"
}
推荐答案
您可以添加计算属性以获取JSON表示形式,并添加静态(类)函数以从Sentence
数组创建JSON数组.
You could add a computed property to get the JSON representation and a static (class) function to create an JSON array from a Sentence
array.
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
协议,该协议提供了一种非常方便的方式来编码和解码自定义结构.
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屋!
查看全文