Answers for "json to string swift"

0

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)
    }
Posted by: Guest on June-03-2020
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 "json to string swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language