title: Automatic JSON serialization and deserialization of objects in Swift
body: <p>I'm looking for a way to automatically serialize and deserialize class instances in Swift. Let's assume we have defined the following class …</p>
  
  <pre><code>class Person {
      let firstName: String
      let lastName: String
  
      init(firstName: String, lastName: String) {
          self.firstName = firstName
          self.lastName = lastName
      }
  }
  </code></pre>
  
  <p>… and <code>Person</code> instance:</p>
  
  <pre><code>let person = Person(firstName: "John", lastName: "Doe")
  </code></pre>
  
  <p>The JSON representation of <code>person</code> would be the following:</p>
  
  <pre><code>{
      "firstName": "John",
      "lastName": "Doe"
  }
  </code></pre>
  
  <p>Now, here are my questions:</p>
  
  <ol>
  <li>How can I serialize the <code>person</code> instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?</li>
  <li>How can I deserialize the above JSON and get back an instantiated object that is statically typed to be of type <code>Person</code>? Again, I don't want to map the properties manually.</li>
  </ol>
  
  <hr>
  
  <p>Here's how you'd do that in C# using <a href="http://james.newtonking.com/json">Json.NET</a>:</p>
  
  <pre><code>var person = new Person("John", "Doe");
  string json = JsonConvert.SerializeObject(person);
  // {"firstName":"John","lastName":"Doe"}
  
  Person deserializedPerson = JsonConvert.DeserializeObject&lt;Person&gt;(json);
  </code></pre>