Swift:将结构转换为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33186051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: Convert struct to JSON?
提问by ixany
I created a structand want to save it as a JSON-file.
我创建了一个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 structobject to something like:
但是我怎样才能将struct对象转换为类似的东西:
{
"sentence": "Hello world",
"lang": "en"
}
回答by vadian
You could add a computed property to get the JSON representation and a static (class) function to create an JSON array from a Sentencearray.
您可以添加一个计算属性来获取 JSON 表示和一个静态(类)函数来从Sentence数组创建一个 JSON数组。
struct Sentence {
var sentence = ""
var lang = ""
static func jsonArray(array : [Sentence]) -> String
{
return "[" + array.map {struct Sentence {
var sentence = ""
var lang = ""
static func jsonArray(array : [Sentence]) -> String
{
return "[" + array.map {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) }
.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"}]
.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"}]
struct Sentence {
var sentence = ""
var lang = ""
func toJSON() -> String? {
let props = ["Sentence": self.sentence, "lang": lang]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(props,
options: .PrettyPrinted)
return String(data: jsonData, encoding: NSUTF8StringEncoding)
} catch let error {
print("error converting to json: \(error)")
return nil
}
}
}
Edit:
编辑:
Swift 4 introduces the Codableprotocol which provides a very convenient way to encode and decode custom structs.
Swift 4 引入了Codable协议,它提供了一种非常方便的方式来编码和解码自定义结构。
struct Sentence: Encodable {
var sentence: String?
var lang: String?
}
let sentence = Sentence(sentence: "Hello world", lang: "en")
回答by Scriptable
Use the NSJSONSerialization class.
Using this for reference, you may need to create a function which returns the JSON serialized string. In this function you could take the required properties and create a NSDictionary from them and use the class mentioned above.
使用此作为参考,您可能需要创建一个返回 JSON 序列化字符串的函数。在此函数中,您可以获取所需的属性并从中创建 NSDictionary 并使用上面提到的类。
Something like this:
像这样的东西:
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(sentence)
Because your struct only has two properties it might be easier to just build the JSON string yourself.
因为您的结构只有两个属性,所以自己构建 JSON 字符串可能会更容易。
回答by Brett
Swift 4supports the Encodable protocol e.g.
Swift 4支持 Encodable 协议,例如
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)
{
"sentence": "Hello world",
"lang": "en"
}
Now you can automatically convert your Struct into JSON using a JSONEncoder:
现在您可以使用 JSONEncoder 自动将您的 Struct 转换为 JSON:
##代码##Print it out:
打印出来:
##代码##
