以下是代码:
// won't compile!
extension Array where Element: JsonSerializable : JsonSerializable {
var JsonRepresentation: AnyObject {
var representation = [AnyObject]()
for obj in self {
representation.append(obj.JsonRepresentation)
}
return representation as AnyObject
}
}
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 AnyObject:
representation[label] = value as AnyObject
default:
break
}
}
return representation as AnyObject
}
func toJson() -> String? {
let representation = JsonRepresentation
// guard JSONSerialization.isValidJSONObject(representation) else {
// return nil
// }
do {
let data = try JSONSerialization.data(withJSONObject: representation, options: [.prettyPrinted])
return String(data: data, encoding: String.Encoding.utf8)
} catch {
return nil
}
}
}
要点是我想要一个JsonSerializables数组也是JsonSerializable。我怎样才能做到这一点?