Skip to content

Instantly share code, notes, and snippets.

@proactive-solutions
Last active December 2, 2016 08:22
Show Gist options
  • Save proactive-solutions/9539b9d753d5463266c0406cc2ad3cd8 to your computer and use it in GitHub Desktop.
Save proactive-solutions/9539b9d753d5463266c0406cc2ad3cd8 to your computer and use it in GitHub Desktop.
Creates JSON representation from the swift struct. Code was copied from this blog, all the credit goes to the original author of the blog http://codelle.com/blog/2016/5/an-easy-way-to-convert-swift-structs-to-json/
protocol JSONRepresentable {
var JSONRepresentation: Any { get }
}
protocol JSONSerializable: JSONRepresentable {
}
extension JSONSerializable {
var JSONRepresentation: Any {
var representation = [String: Any]()
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
}
}
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
}
}
}
extension Date: JSONRepresentable {
var JSONRepresentation: Any {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return formatter.string(from: self)
}
}
struct Event: JSONSerializable {
var name: String
var timestamp: NSDate
}
let event = Event(name: "Something happened", timestamp: NSDate())
if let json = event.toJSON() {
print(json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment