swift将struct转化为json
struct Car: JSONSerializable {
let car = Car(manufacturer: "Tesla",model: "Model T",mileage: 1234.56,owner: Owner(name: "Emil"))
// // 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 } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |