Swift中对象的自动JSON序列化和反序列化 [英] Automatic JSON serialization and deserialization of objects in Swift
问题描述
我正在寻找一种在Swift中自动序列化和反序列化类实例的方法.假设我们定义了以下类……
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
}
}
…和Person
实例:
let person = Person(firstName: "John", lastName: "Doe")
person
的JSON表示形式如下:
The JSON representation of person
would be the following:
{
"firstName": "John",
"lastName": "Doe"
}
现在,这是我的问题:
- 如何序列化
person
实例并获取上述JSON,而不必手动将类的所有属性添加到变成JSON的字典中? - 如何反序列化上面的JSON并获取静态类型为
Person
的实例化对象?同样,我不想手动映射属性.
- 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.
以下是您使用C#使用 Json.NET 的方式:
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);
推荐答案
如 WWDC2017 @ 24:48( Swift 4 ),我们将能够使用Codable协议.例子
As indicated in WWDC2017 @ 24:48 (Swift 4), we will be able to use the Codable protocol. Example
public struct Person : Codable {
public let firstName:String
public let lastName:String
public let location:Location
}
序列化
let payload: Data = try JSONEncoder().encode(person)
反序列化
let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)
请注意,所有属性都必须符合Codable协议.
Note that all properties must conform to the Codable protocol.
替代可以是 JSONCodable ,由 Swagger的代码生成器.
An alternative can be JSONCodable which is used by Swagger's code generator.
这篇关于Swift中对象的自动JSON序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!