2013-12-14 85 views
0

我有問題反序列化這個來自API的JSON數據結構。 我們沒有可能更改JSON數據,所以我需要按照原樣序列化它。反序列化動態密鑰到字典中的JSON

{"success":"1","return":{"balances_available":{"ALF":"0.00000000","AMC":"0.00000000","ADT":"0.00000000","ANC":"0.00000000"}}} 

目前我試試這個

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Response)); 
balances = serializer.ReadObject(ms) as Response; 

[DataContract] 
public class Response 
{ 
    [DataMember(Name = "success")] 
    public int Status { get; set; } 

    [DataMember(Name = "return")] 
    public Balance Return { get; set; } 
} 

[DataContract] 
public class Balance 
{ 
    [DataMember(Name = "balances_available")] 
    public Dictionary<string, string> BalancesAvailable { get; set; } 
} 

但我的字典中得到0的項目,所以它看起來並不像它beeing序列化。 除了手動創建定義所有平衡項(ALF,AMC等)的類之外,是否沒有其他解決方法?

回答

1

您必須添加DataContractJsonSerializerSettings這樣的:

var settings = new DataContractJsonSerializerSettings 
        { 
         UseSimpleDictionaryFormat = true 
        }; 
var serializer = new DataContractJsonSerializer(typeof(Response), settings); 

,這將是工作。祝你好運!

+0

完美!它的作品,非常感謝:) – Martin