-
-
Save yury2me/3e53113bfc16511b9202496b37a05dcc to your computer and use it in GitHub Desktop.
Polymorphic JSON Encoding ignores Subclass properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name" : "Paul", | |
"age" : 47 | |
} | |
{ | |
"name" : "David", | |
"age" : 28 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class Person: Encodable { | |
var name: String | |
var age: Int | |
init(name: String, age: Int) { | |
self.name = name | |
self.age = age | |
} | |
} | |
class Worker: Person { | |
var job: String | |
init(job: String, name: String, age: Int) { | |
self.job = job | |
super.init(name: name, age: age) | |
} | |
} | |
var paul = Person(name: "Paul", age: 47) | |
var baker = Worker(job: "Baker", name: "David", age: 28) | |
var jsonEncoder = JSONEncoder() | |
jsonEncoder.outputFormatting = .prettyPrinted | |
var jsonDataPaul = try jsonEncoder.encode(paul) | |
var jsonPaul = String(data: jsonDataPaul, encoding: String.Encoding.utf8)! | |
print(jsonPaul) | |
print("\n") | |
var jsonDataBaker = try jsonEncoder.encode(baker) | |
var jsonBaker = String(data: jsonDataBaker, encoding: String.Encoding.utf8)! | |
print(jsonBaker) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment