2011-12-05 21 views
3

我不喜歡DataContractSerializer如何處理我的Dictionary反序列化。我的方法都返回一個Stream,我使用JavascriptDeserializer來返回我想要的JSON,但是這對Dictionary的幫助並不是我的一個參數。WCF - 如何使用JavascriptSerializer作爲我的Deserializer?

的JavascriptSerializer處理詞典的像這樣的:

{"myKey1":"myValue1", "myKey2":"myValue2"} 

DataContractSerializer的做到這一點:

[{"Key":"myKey1", "Value":"myValue1"}, {"Key":"myKey2", "Value":"myValue2"}] 

的問題,這是我們的Android和iPhone應用程序是嘔吐本地生成的代碼和我們的AJAX通話失敗。

任何簡單的方法來做到這一點或一種方法來解決微軟可怕的Dictionary反序列化?

+0

你有重複你的問題http://stackoverflow.com/questions/8372076/wcf-post-json-dictionary-without-key-value-text - 請刪除其中之一。 Thankyou –

回答

0
+0

這不回答我的問題。我需要知道如何對字典進行反序列化。這不是一個返回的字典,而是一個由客戶端應用程序傳給我的字典。 DataContract *序列化程序不像我們所有的客戶端序列化字典那樣處理字典反序列化。 – Brandon

+0

http://stackoverflow.com/questions/4199321/how-to-deserialize-a-dictionary-using-datacontractjsonserializer – ttomsen

2

我有同樣的問題。我通過使用實現ISerializable的自定義Dictionary(實際上是一個包裝器)來解決它。

[Serializable] 
public class CustomDictionary: ISerializable 
{ 
    /// <summary> 
    /// Inner object. 
    /// </summary>   
    private Dictionary<string, string> innerDictionary; 

    public CustomDictionary() 
    { 
     innerDictionary = new Dictionary<string, string>(); 
    } 

    public CustomDictionary(IDictionary<string, string> dictionary) 
    { 
     innerDictionary = new Dictionary<string, string>(dictionary); 
    } 

    public Dictionary<string, string> InnerDictionary 
    { 
     get { return this.innerDictionary; } 
    } 

    //Used when deserializing 
    protected CustomDictionary(SerializationInfo info, StreamingContext context) 
    { 
     if (object.ReferenceEquals(info, null)) throw new ArgumentNullException("info"); 
     innerDictionary = new Dictionary<string, string>(); 
     foreach (SerializationEntry entry in info) 
     { 
      innerDictionary.Add(entry.Name, entry.Value as string); 
     } 
    } 

    //Used when serializing 
    protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     if (!object.ReferenceEquals(info, null)) 
     { 
      foreach (string key in innerDictionary.Keys) 
      { 
       string value = innerDictionary[key]; 
       info.AddValue(key, value); 
      } 
     } 
    } 

    //Add methods calling InnerDictionary as necessary (ContainsKey, Add, etc...) 
} 
+0

我見過類似的解決方案。 –

相關問題