2009-06-04 48 views
4

鑑於這樣的對象:如何只序列某些對象屬性

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" } 

我已經寫了使用JavaScriptSerializer從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" } 
} 

但我想解串器的工作方式稍有不同:

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,二進制,YAML,...)的罰款。

回答

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; 
} 

然後,而不是序列化原始對象,你通過字典和鮑勃的你的叔叔。

23

很簡單 - 只需用[ScriptIgnore]屬性來修飾您希望忽略的方法即可。

+0

我希望它更具活力。所以我可以序列化A,B或C,D。 – alex2k8 2009-06-04 12:44:48

+4

然後你從錯誤的角度來看待這個問題 - 本地序列化是關於序列化對象的。可能最好的辦法是創建兩個對象 - 一個用於A和B,一個用於C和D,然後根據需要序列化它們中的任意一個。 – 2009-06-04 15:43:56

1

那麼「[NonSerialized()]」屬性標籤呢?

class Foo 
    { 
     field A; 

     [NonSerialized()] 
     field B; 

     [NonSerialized()] 
     field C; 

     field D; 
    } 
相關問題