2013-12-19 24 views
1

我有以下代碼:如何序列化匿名對象到JSON,而不包括屬性名

///<summary> 
///In this case you can set any other valid attribute for the editable element. 
///For example, if the element is edittype:'text', we can set size, maxlength, 
///etc. attributes. Refer to the valid attributes for the element 
///</summary> 
public object OtherOptions { get; set; } 
public override string ToString() 
{ 
    return this.ToJSON(); 
} 

我需要從OtherOptions屬性的匿名對象和序列化匿名對象的每個屬性,因爲它是從主要的對象。

如:

OtherOptions = new { A = "1", B = "2" } 

如果我序列化,這將是(或像這樣):

OtherOptions: { 
A: "1", 
B: "2" 
} 

是否有可能有A和B在同一水平OtherOptions無明確地刪除它。

+1

簡答:沒有。您將不得不與對象圖形拼合或使用自定義對象序列化。 – user2864740

回答

2

好吧,這只是醜陋,我不建議這樣做,但它你想要做什麼......

從本質上講,它創造你想要的屬性的解釋和再序列那本字典。

static void Main(string[] args) 
    { 
     JavaScriptSerializer serializer = new JavaScriptSerializer(); 

     var obj = new {Prop1 = "val1", OtherOptions = new {A = "1", B = "2"}}; 

     IDictionary<string, object> result = new Dictionary<string, object>(); 
     foreach (var kv in GetProps(obj)) 
     { 
      if (!kv.Key.Equals("OtherOptions")) 
       result.Add(kv); 
     } 
     foreach (var kv in GetProps(obj.OtherOptions)) 
     { 
      result.Add(kv); 
     } 
     var serialized = serializer.Serialize(result); 
    } 

    static IEnumerable<KeyValuePair<string, object>> GetProps(object obj) 
    { 
     var props = TypeDescriptor.GetProperties(obj); 
     return 
      props.Cast<PropertyDescriptor>() 
       .Select(prop => new KeyValuePair<string, object>(prop.Name, prop.GetValue(obj))); 
    } 

系列化變得

{"Prop1":"val1","A":"1","B":"2"} 

你可以在你想忽略,然後檢查在GetProps方法屬性,而不是返回,如果存在野外使用的屬性。

同樣,我不建議這樣做。