“Konversi data ke JSON Swift” Kode Jawaban

Konversi data ke JSON Swift

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

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

string ke json swift

  let jsonText = "{\"first_name\":\"Sergey\"}"
        var dictonary:NSDictionary?
        
        if let data = jsonText.data(using: String.Encoding.utf8) {
            
            do {
                dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
            
                if let myDictionary = dictonary
                {
                     print(" First name is: \(myDictionary["first_name"]!)")
                }
            } catch let error as NSError {
                print(error)
            }
        }
Dero Nara

Jawaban yang mirip dengan “Konversi data ke JSON Swift”

Pertanyaan yang mirip dengan “Konversi data ke JSON Swift”

Lebih banyak jawaban terkait untuk “Konversi data ke JSON Swift” di Swift

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya