我在从API中反序列化此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个项目,所以它看起来并不像是序列化了。 除了手动创建一个定义所有余额项目(ALF,AMC等)的类之外,没有其他方法可以解决这个问题吗?
答案 0 :(得分:2)
您必须像这样添加DataContractJsonSerializerSettings
:
var settings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
var serializer = new DataContractJsonSerializer(typeof(Response), settings);
这将是有效的。祝你好运!