我正在寻找一种在SWIFT中自动序列化和反序列化类实例的方法.让我们假设我们已经定义了以下类…
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
…还有Person
个例子:
let person = Person(firstName: "John", lastName: "Doe")
person
的JSON表示如下所示:
{
"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? - 如何反序列化上面的JSON并返回一个静态类型为
Person
的实例化对象?同样,我不想手动映射属性.
以下是在C#中使用Json.NET时如何做到这一点:
var person = new Person("John", "Doe");
string json = JsonConvert.SerializeObject(person);
// {"firstName":"John","lastName":"Doe"}
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);