Given such 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 have wrote some 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 { o.A, o.D });
string serialized = Serialize(foo, filter);
// {"A":"a","D":"d"}
Foo deserialized = Deserialize<Foo>(serialized);
// { A = "a", B = null, C = null, D = "d" }
}
But I would like the deserializer to work a bit 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, may be there are some better or existing alternatives available?
EDIT:
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.
EDIT 2:
Any serialization solutions (JSON, XML, Binary, Yaml, ...) are fine.