当内部 属性 名称不同时反序列化 JSON
Deserializing JSON when inner property names vary
我有 JSON 看起来像这样(外部 JSON 超出我的控制):
[
{
"currencies": {
"KGS": {
"name": "Kyrgyzstani som",
"symbol": "с"
}
}
},
{
"currencies": {
"SOS": {
"name": "Somali shilling",
"symbol": "Sh"
}
}
}
]
我有一组 类,我希望将此 JSON 反序列化为
public class ParentClass
{
public OuterClass Currencies { get; set; }
}
public class OuterClass
{
//Inner property below needs to map to these changing prop names: "KGS", "SOS"
public InnerClass Inner { get; set; }
}
public class InnerClass
{
public string Name { get; set; }
public string Symbol { get; set; }
}
最后,当我尝试反序列化时:
JsonConvert.DeserializeObject<IList<ParentClass>>(responseBody.Content);
它没有正确反序列化,因为它无法将不同的 属性 名称映射到“内部”。有没有办法处理这种情况?
Newtonsoft 似乎没有任何问题..
public partial class Blah
{
[JsonProperty("currencies")]
public Dictionary<string, Currency> Currencies { get; set; }
}
public partial class Currency
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
}
和
var blah = JsonConvert.DeserializeObject<Blah[]>(jsonString);
..虽然可能值得注意我认为你有你的 parent 并且如果这个 json 只是一个片段,那么外面的方向是错误的..
我有 JSON 看起来像这样(外部 JSON 超出我的控制):
[
{
"currencies": {
"KGS": {
"name": "Kyrgyzstani som",
"symbol": "с"
}
}
},
{
"currencies": {
"SOS": {
"name": "Somali shilling",
"symbol": "Sh"
}
}
}
]
我有一组 类,我希望将此 JSON 反序列化为
public class ParentClass
{
public OuterClass Currencies { get; set; }
}
public class OuterClass
{
//Inner property below needs to map to these changing prop names: "KGS", "SOS"
public InnerClass Inner { get; set; }
}
public class InnerClass
{
public string Name { get; set; }
public string Symbol { get; set; }
}
最后,当我尝试反序列化时:
JsonConvert.DeserializeObject<IList<ParentClass>>(responseBody.Content);
它没有正确反序列化,因为它无法将不同的 属性 名称映射到“内部”。有没有办法处理这种情况?
Newtonsoft 似乎没有任何问题..
public partial class Blah
{
[JsonProperty("currencies")]
public Dictionary<string, Currency> Currencies { get; set; }
}
public partial class Currency
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
}
和
var blah = JsonConvert.DeserializeObject<Blah[]>(jsonString);
..虽然可能值得注意我认为你有你的 parent 并且如果这个 json 只是一个片段,那么外面的方向是错误的..