當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Swift如何实现与JSON互转
生活随笔
收集整理的這篇文章主要介紹了
Swift如何实现与JSON互转
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JSONDecoder與JSONEncoder
通過 Codable 協(xié)議實(shí)現(xiàn)Swift對(duì)象與JSON字符串之間的互轉(zhuǎn)。
public typealias Codable = Decodable & EncodableCodable 是 Decodable 和 Encodable 的類型別名。當(dāng)你遵守 Codable 協(xié)議時(shí),同時(shí)遵守Decodable 和 Encodable 協(xié)議。
Swift 標(biāo)準(zhǔn)庫類型都實(shí)現(xiàn)了 Codable , 比如 String , Double , Int 等, Foundation 庫中也有許多類型實(shí)現(xiàn)了 Codable , 比如 Date , Data , URL , Array, Dictionary, Optional.
import Foundation// MARK: - Decodestruct User { // 基本類型組合默認(rèn)遵守Codable協(xié)議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
總結(jié)
以上是生活随笔為你收集整理的Swift如何实现与JSON互转的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LIME-AI可解释模型:《“Why S
- 下一篇: JSP页面显示源码