當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Swift如何实现与JSON互转
生活随笔
收集整理的這篇文章主要介紹了
Swift如何实现与JSON互转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JSONDecoder與JSONEncoder
通過 Codable 協議實現Swift對象與JSON字符串之間的互轉。
public typealias Codable = Decodable & EncodableCodable 是 Decodable 和 Encodable 的類型別名。當你遵守 Codable 協議時,同時遵守Decodable 和 Encodable 協議。
Swift 標準庫類型都實現了 Codable , 比如 String , Double , Int 等, Foundation 庫中也有許多類型實現了 Codable , 比如 Date , Data , URL , Array, Dictionary, Optional.
import Foundation// MARK: - Decodestruct User { // 基本類型組合默認遵守Codable協議var name: Stringvar age: Int }let jsonStr = """ {"name": "Ryan","age": 18 } """let jsonData = jsonStr.data(using: .utf8)!let decoder = JSONDecoder()do {let userObj = try decoder.decode(User.self, from: jsonData)print("userObj = \(userObj)") } catch {print("decode error") }// MARK: - Encodelet user = User(name: "Lux", age: 20)let encoder = JSONEncoder()do {let data = try encoder.encode(user)let jsonStr = String(data: data, encoding: .utf8)!print("jsonStr = \(jsonStr)") } catch {print("encode error") }JSON -> Object
Object -> JSON
總結
以上是生活随笔為你收集整理的Swift如何实现与JSON互转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LIME-AI可解释模型:《“Why S
- 下一篇: 递归分形--山脉