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/322902.html