Answers for "convert json to data in swift"

2

convert data to json swift

do{  
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}catch{ print("erroMsg") }
Posted by: Guest on January-13-2022
0

struct to json convert in swift

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) }
Posted by: Guest on May-19-2021

Code answers related to "convert json to data in swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language