swift将struct转化为json

前端之家收集整理的这篇文章主要介绍了swift将struct转化为json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。









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相关文章