title: How to serialize only certain object properties
body: <p>Given such object:        </p>
  
  <pre><code>Foo foo = new Foo
  {
      A = "a",
      B = "b",
      C = "c",
      D = "d"
  };
  </code></pre>
  
  <p>How can I serialize and deserialize only certain properties (e.g. A and D).</p>
  
  <pre><code>Original: 
    { A = "a", B = "b", C = "c", D = "d" }
  
  Serialized:
    { A = "a", D = "d" }
  
  Deserialized:
    { A = "a", B = null, C = null, D = "d" }
  </code></pre>
  
  <p>I have wrote some code using JavaScriptSerializer from System.Web.Extensions.dll:</p>
  
  <pre><code>public string Serialize&lt;T&gt;(T obj, Func&lt;T, object&gt; filter)
  {
      return new JavaScriptSerializer().Serialize(filter(obj));
  }
  
  public T Deserialize&lt;T&gt;(string input)
  {
      return new JavaScriptSerializer().Deserialize&lt;T&gt;(input);
  }
  
  void Test()
  {
      var filter = new Func&lt;Foo, object&gt;(o =&gt; new { o.A, o.D });
  
      string serialized = Serialize(foo, filter);
      // {"A":"a","D":"d"}
  
      Foo deserialized = Deserialize&lt;Foo&gt;(serialized);
      // { A = "a", B = null, C = null, D = "d" }
  }
  </code></pre>
  
  <p>But I would like the deserializer to work a bit differently:</p>
  
  <pre><code>Foo output = new Foo
  {
      A = "1",
      B = "2",
      C = "3",
      D = "4"
  };
  
  Deserialize(output, serialized);
  // { A = "a", B = "2", C = "3", D = "d" }
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>Also, may be there are some better or existing alternatives available?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>There was some suggestions to use attributes to specify serializable fields. I am looking for more dynamic solution. So I can serialize A, B and the next time C, D.</p>
  
  <p><strong>EDIT 2:</strong></p>
  
  <p>Any serialization solutions (JSON, XML, Binary, Yaml, ...) are fine.</p>