swift将struct转化为json

swift将struct转化为json,第1张

概述 struct Car: JSONSerializable {         var manufacturer: String         var model: String         var mileage: Float                  var owner: Owner     }          struct Owner: JSONSerializable {









struct Car: JsONSerializable {
var manufacturer: String
var model: String
var mileage: float

var owner: Owner
}

struct Owner: JsONSerializable {
var name: String
}



let car = Car(manufacturer: "Tesla",model: "Model T",mileage: 1234.56,owner: Owner(name: "Emil"))

if let Json = car.toJsON() {
print(Json)

}



// // JsONSerializable.swift // Longsheng // // Created by 关洪昌 on 16/9/30. // copyright © 2016年 夸克时代. All rights reserved. // protocol JsONRepresentable { var JsONRepresentation: AnyObject { get } } protocol JsONSerializable: JsONRepresentable { } extension JsONSerializable { var JsONRepresentation: AnyObject { var representation = [String: AnyObject]() for case let (label?,value) in Mirror(reflecting: self).children { switch value { case let value as JsONRepresentable: representation[label] = value.JsONRepresentation case let value as NSObject: representation[label] = value default: // Ignore any unserializable propertIEs break } } return representation as AnyObject } } extension JsONSerializable { func toJsON() -> String? { let representation = JsONRepresentation guard JsONSerialization.isValIDJsONObject(representation) else { return nil } do { let data = try JsONSerialization.data(withJsONObject: representation,options: []) return String(data: data,enCoding: String.EnCoding.utf8) } catch { return nil } } }

总结

以上是内存溢出为你收集整理的swift将struct转化为json全部内容,希望文章能够帮你解决swift将struct转化为json所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071477.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存