jsonswiftstructnsjsonserialization

Swift: Convert struct to 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)

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

Solution

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