Swift:将struct转换为JSON?

时间:2015-10-17 11:23:03

标签: json swift struct nsjsonserialization

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

4 个答案:

答案 0 :(得分:17)

您可以添加一个计算属性来获取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) }

答案 1 :(得分:11)

使用NSJSONSerialization class

将此项用于reference,您可能需要创建一个返回JSON序列化字符串的函数。在此函数中,您可以获取所需的属性并从中创建NSDictionary并使用上面提到的类。

这样的事情:

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
        }
    }

}

因为你的struct只有两个属性,所以自己构建JSON字符串可能更容易。

答案 2 :(得分:10)

Swift 4 支持Encodable协议,例如

struct Sentence: Encodable {
    var sentence: String?
    var lang: String?
}

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

现在,您可以使用JSONEncoder自动将Struct转换为JSON:

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(sentence)

打印出来:

let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)

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

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

答案 3 :(得分:1)

这是一个很好的扩展和 JSON 编码/解码方法:

extension Encodable {
    
    func toJSONString() -> String {
        let jsonData = try! JSONEncoder().encode(self)
        return String(data: jsonData, encoding: .utf8)!
    }
    
}

func instantiate<T: Decodable>(jsonString: String) -> T? {
    return try? JSONDecoder().decode(T.self, from: jsonString.data(using: .utf8)!)
}

示例用法:

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

let sentence = Sentence(sentence: "Hello world", lang: "en")
let jsonStr = sentence.toJSONString()
print(jsonStr)      // prints {"lang":"en","sentence":"Hello world"}

let sentenceFromJSON: Sentence? = instantiate(jsonString: jsonStr)
print(sentenceFromJSON!)    // same as original sentence