鉴于此类对象:
Foo foo = new Foo
{
A = "a",
B = "b",
C = "c",
D = "d"
};
如何仅序列化和反序列化某些属性(例如A和D)。
Original:
{ A = "a", B = "b", C = "c", D = "d" }
Serialized:
{ A = "a", D = "d" }
Deserialized:
{ A = "a", B = null, C = null, D = "d" }
我使用System.Web.Extensions.dll中的JavaScriptSerializer编写了一些代码:
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" }
}
但我希望解串器的工作方式略有不同:
Foo output = new Foo
{
A = "1",
B = "2",
C = "3",
D = "4"
};
Deserialize(output, serialized);
// { A = "a", B = "2", C = "3", D = "d" }
有什么想法吗?
此外,可能有更好的或现有的替代品?
修改
有一些建议要使用属性来指定可序列化字段。我正在寻找更有活力的解决方案。所以我可以序列化A,B和下一次C,D。
编辑2:
任何序列化解决方案(JSON,XML,Binary,Yaml,...)都可以。
答案 0 :(得分:24)
非常简单 - 只需使用[ScriptIgnore]
属性修饰您要忽略的方法。
答案 1 :(得分:4)
我过去曾经使用Javascript Serializer做过类似的事情。在我的例子中,我只想序列化包含值的对象中的可空属性。我这样做是通过使用反射,检查属性的值并将属性添加到字典,例如
public static Dictionary<string,object> CollectFilledProperties(object instance)
{
Dictionary<string,object> filledProperties = new Dictionary<string,object>();
object data = null;
PropertyInfo[] properties = instance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
data = property.GetValue(instance, null);
if (IsNullable(property.PropertyType) && data == null)
{
// Nullable fields without a value i.e. (still null) are ignored.
continue;
}
// Filled has data.
filledProperties[property.Name] = data;
}
return filledProperties;
}
public static bool IsNullable(Type checkType)
{
if (checkType.IsGenericType && checkType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// We are a nullable type - yipee.
return true;
}
return false;
}
然后,不是序列化原始对象,而是传递字典,而鲍勃是你的叔叔。
答案 2 :(得分:3)
有些属性可以应用于控制序列化的类和/或属性。 Attributes that control serialization
答案 3 :(得分:1)
[NonSerialized()]
属性标记怎么样?
class Foo
{
field A;
[NonSerialized()]
field B;
[NonSerialized()]
field C;
field D;
}