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