[英]Deserializing JSON with dynamic keys into dictionary
I have problems deserializing this JSON data structure comming from an API. 我在反序列化来自API的JSON数据结构时遇到问题。 We have no possibilities to change the JSON data, so I need to serialize it as it is.
我们无法更改JSON数据,因此我需要按原样对其进行序列化。
{"success":"1","return":{"balances_available":{"ALF":"0.00000000","AMC":"0.00000000","ADT":"0.00000000","ANC":"0.00000000"}}}
Currently I try this 目前我尝试这个
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; }
}
But my dictionary get 0 items, so it does not look like it is beeing serialized. 但是我的字典有0个项目,因此它看起来像不是在序列化。 Are there no other way of fixing this than manually creating a class where I define all balance items (ALF, AMC, etc.)?
除了手动创建一个我定义所有余额项目(ALF,AMC等)的类之外,没有其他方法可以解决此问题?
You must add DataContractJsonSerializerSettings
like this: 您必须像这样添加
DataContractJsonSerializerSettings
:
var settings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
var serializer = new DataContractJsonSerializer(typeof(Response), settings);
And this will be work. 这将是可行的。 Good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.