Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" } 
like image 687
ixany Avatar asked Oct 17 '15 11:10

ixany


1 Answers

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) } 
like image 189
vadian Avatar answered Oct 25 '22 23:10

vadian