Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

Automatic JSON serialization and deserialization of objects in 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
    }
}

… 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:

  1. 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?
  2. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As shown 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
}

To serialize

let payload: Data = try JSONEncoder().encode(person)

To deserialize

let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger's code generator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...