Struct To Json Convert In Swift

[Solved] Struct To Json Convert In Swift | Swift - Code Explorer | yomemimo.com
Question : convert data to json swift

Answered by : ahsan-lwa8tagab3go

do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}catch{ print("erroMsg") }

Source : https://stackoverflow.com/questions/39427500/swift-3-0-data-to-json-string-any | Last Update : Thu, 20 Jan 22

Question : struct to json convert in swift

Answered by : gifted-gerbil-jijipubuxs7w

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

Source : https://stackoverflow.com/questions/33186051/swift-convert-struct-to-json | Last Update : Wed, 26 May 21

Answers related to struct to json convert in swift

Code Explorer Popular Question For Swift