letdecoder=JSONDecoder()letproduct=trydecoder.decode(GroceryProduct.self,from:json)print(product.name)// Prints "Durian" 这里要注意 GroceryProduct 结构体需要遵循 Codable,因为 JSONDecoder 的实例对象的 decode 方法需要遵循 Decodable 协议的结构体。Codable 是 Encodable 和 Decodable 两个协议的组合,写法如下...
使用JSONDecoder进行解码。可以通过以下代码将JSON数据解码为Person对象: 代码语言:swift 复制 letjson=""" { "name": "John", "age": 30, "email": "john@example.com" } """letjsonData=json.data(using:.utf8)!letdecoder=JSONDecoder()do{letperson=trydecoder.decode(Person.self,from:jsonData)prin...
使用Codable 协议是 Swift 中解析 JSON 的推荐方式。首先,你需要定义一个对应的数据模型,该模型需要符合 Codable 协议。然后使用 JSONDecoder 对象将 JSON 数据解析为对应的数据模型对象。 示例代码: struct MyData: Codable { var name: String var age: Int } if let url = Bundle.main.url(forResource: "...
let decoder = JSONDecoder() try { let user = try? decoder.decode(User.self, data: jsonData3) } catch { // json3 格式会进入该分支 print("decode user error") } 上述代码中,json1 和 json2 可以正确反序列化成 User 结构,json3 由于 “shenzhen” 无法转化成 City,导致整个 User 结构解析失...
do{// 创建 JSONDecoder 实例letdecoder=JSONDecoder()// 解码 JSON 数据letuser=trydecoder.decode(User.self,from:jsonData)// 打印解码后的用户信息print("User ID:\(user.id)")print("User Name:\(user.name)")print("User Email:\(user.email)")}catch{// 处理解码错误print("Error decoding JSON...
Swift 4.0 之后官方推出的 JSON 序列化方案,可以理解为 Unbox+Sourcery 的组合,编译器会根据数据结构定义,自动生成编解码逻辑,开发者使用特定的 Decoder/Encoder 对数据进行转化处理。 Codable 作为 Swift 官方推出的方案,使用者可以无成本的接入。不过在具体实践过程中,碰到了一些问题 ...
JSONDecoder().decode(User.self, from: data) { print(user.username) // 输出: JohnDoe print(user.age) // 输出: 0,因为age被设置成了-5,didSet中进行了修正 } 在上面的例子中,我们定义了一个User结构体,它实现了Codable协议,并包含一个age属性,该属性具有一个didSet观察器。当age的值被解码并设置时...
let employeeADecoded=try? jsonDecoder.decode(Employee.self, from: jsonData!) print(employeeADecoded!) //result /* jsonData: Optional(54 bytes) jsonString: Optional("{\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}") ...
// 将JSON字符串转成 DataletjsonData:Data=jsonString.data(using:String.Encoding.utf8)!// 将 data 转成对象letdecoder=JSONDecoder()do{// 解码得到player对象letplayer:Player=trydecoder.decode(Player.self,from:jsonData)// 打印print(player)print(player.name)}catch{} ...
let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let weather = try decoder.decode(WeatherData.self, from: data) return weather } 最后,JSON数据看起来像这样 { "coord": { "lon": 13.3776, "lat": 49.7475