how to decode json in swift code example
Example 1: 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)")
Example 2: JSONDecoder
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name)