swift 可编码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 可编码相关的知识,希望对你有一定的参考价值。
json格式如下
```json
{
"AP name": "AP888",
"Band": "2.4G",
"Block": "C",
"Floor": "15",
"Location": "C09-ST1",
"SSID": "OUHK-Staff"
}
```
我使用了[Paste JSON as Code • quicktype](https://itunes.apple.com/hk/app/paste-json-as-code-quicktype/id1330801220?mt=12)
![IMAGE](quiver-image-url/067C2AC04741309C9A807C89DDE4914A.jpg =1392x863)
```swift
do{
let decoder = JSONDecoder()
let wifiInfo = try decoder.decode(WiFi.self, from: (data!))
print(wifiInfo.location)
}catch let error{
print(error)
}
```
> Result : C09-ST1
-----
## to json
```swift
import UIKit
import Firebase
class User:Codable {
let email: String
var studentId: String?
let name: String
var persistedFaceIds: [String:String]?
var personId: String?
init() {
self.email = (Auth.auth().currentUser?.email)!
self.name = (Auth.auth().currentUser?.displayName)!
self.persistedFaceIds = [:]
self.studentId = ""
self.personId = ""
}
func getJson() -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(self)// self = 當前user
let encodedString = String(data: data, encoding: .utf8)!
return encodedString
}
func getData() -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(self)
return data
}
}
```
//Empty
以上是关于swift 可编码的主要内容,如果未能解决你的问题,请参考以下文章
如何在可编码结构中使用计算属性(swift)
Swift 可编码解析 keyNotFound
带有可编码数组的 swift 5 抽象网络响应
swift 可编码
swift 可编码+ UserDefaults
将可编码结构编码为 Alamofire POST 参数 - Swift