Answers for "swift struct to json"

3

swift parse json

let string = #"{"name": "watashi", "number": 42, "pi": 3.141592, "array": [2, 3, 5, 7, 11, 13]}"#

let data = string.data(using: .utf8)!
let object = try! JSONSerialization.jsonObject(with: data, options: [])

let jsonObject = object as! [String: Any]

let nameField   = jsonObject["name"]    as? String
let numberField = jsonObject["number"]  as? Int
let piField     = jsonObject["pi"]      as? Double
let arrayField  = jsonObject["array"]   as? [Any]

print("The name argument is \(nameField)")
print("The number is \(numberField)")
print("The value of pi is \(piField)")
print("the array value is \(arrayField)")
Posted by: Guest on February-12-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
-1

swift convert array to json

func json(from object:Any) -> String? {
    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
        return nil
    }
    return String(data: data, encoding: String.Encoding.utf8)
}
Posted by: Guest on June-13-2020

Code answers related to "Swift"

Browse Popular Code Answers by Language