json to string swift code example

Example 1: stringify json swift

do {
        let arrJson = try JSONSerialization.data(withJSONObject: dataAddress, options: JSONSerialization.WritingOptions.prettyPrinted)
        let string = String(data: arrJson, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        let tempJson = string! as String
        print("%%%%%%",tempJson)
    }catch let error as NSError{
        print(error.description)
    }

Example 2: 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) }