Swift: Convert struct to JSON?

时光毁灭记忆、已成空白 提交于 2019-11-26 17:23:09

问题


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)

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

回答1:


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

Edit:

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



回答2:


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.

Something like this:

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

}

Because your struct only has two properties it might be easier to just build the JSON string yourself.




回答3:


Swift 4 supports the Encodable protocol e.g.

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

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

Now you can automatically convert your Struct into JSON using a JSONEncoder:

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

Print it out:

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



来源:https://stackoverflow.com/questions/33186051/swift-convert-struct-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!