I'm looking for a way to automatically serialize and deserialize class instances in Swift. Let's assume we have defined the following class …
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
… and Person
instance:
let person = Person(firstName: "John", lastName: "Doe")
The JSON representation of person
would be the following:
{
"firstName": "John",
"lastName": "Doe"
}
Now, here are my questions:
- How can I serialize the
person
instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?
- How can I deserialize the above JSON and get back an instantiated object that is statically typed to be of type
Person
? Again, I don't want to map the properties manually.
Here's how you'd do that in C# using Json.NET:
var person = new Person("John", "Doe");
string json = JsonConvert.SerializeObject(person);
// {"firstName":"John","lastName":"Doe"}
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);
question from:
https://stackoverflow.com/questions/26820720/automatic-json-serialization-and-deserialization-of-objects-in-swift 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…