gpt4 book ai didi

c# - 使用可变属性名称反序列化 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:07 25 4
gpt4 key购买 nike

我想反序列化来自 here. 的 json

类似于此:

{
"BW": {
"Neujahrstag": {
"datum": "2017-01-01",
"hinweis": ""
},
"Heilige Drei K\u00f6nige": {
"datum": "2017-01-06",
"hinweis": ""
},
"Gr\u00fcndonnerstag": {
"datum": "2017-04-13",
"hinweis": "Gem\u00e4\u00df \u00a7 4 Abs. 3 des Feiertagsgesetzes von Baden-W\u00fcrttemberg[10] haben Sch\u00fcler am Gr\u00fcndonnerstag und am Reformationstag schulfrei. In der Regel legt das Kultusministerium die Ferientermine so fest, dass diese beiden Tage in die Osterferien bzw. in die Herbstferien fallen."
},
"Karfreitag": {
"datum": "2017-04-14",
"hinweis": ""
}
},
"BY": {
"Neujahrstag": {
"datum": "2017-01-01",
"hinweis": ""
},
"Heilige Drei K\u00f6nige": {
"datum": "2017-01-06",
"hinweis": ""
}
}

我想反序列化为:

public class Root
{
public State[] States { get; set; }
}

public class State
{
public Holiday[] Holidays { get; set; }
}

public class Holiday
{
public DateTime Date { get; set; }
public string Note { get; set; }
}

但由于属性名称不固定,我无法执行此操作。

我也尝试过使用 JObject.Parse() 但这对我帮助不大。

关于如何执行此操作的任何想法?

最佳答案

如果您将模型修改为:

public class Root : Dictionary<string, State> { }

public class State : Dictionary<string, Holiday> { }

public class Holiday {
[JsonProperty(PropertyName = "datum")]
public DateTime Date { get; set; }

[JsonProperty(PropertyName = "hinweis")]
public string Note { get; set; }
}

你可以使用这个反序列化:

var root = JsonConvert.DeserializeObject<Root>(str);
var firstBwHoliday = root["BW"]?["Neujahrstag"].Date;

关于c# - 使用可变属性名称反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47507667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com