gpt4 book ai didi

c# - 如何解析会导致非法 C# 标识符的 JSON 字符串?

转载 作者:IT老高 更新时间:2023-10-28 12:47:10 25 4
gpt4 key购买 nike

我一直在使用NewtonSoft JSON Convert库来解析 JSON 字符串并将其转换为 C# 对象。但是现在我遇到了一个非常尴尬的 JSON 字符串,我无法将它转换为 C# 对象,因为我无法用这个 JSON 字符串创建 C# 类。

这是 JSON 字符串

{
"1": {
"fajr": "04:15",
"sunrise": "05:42",
"zuhr": "12:30",
"asr": "15:53",
"maghrib": "19:18",
"isha": "20:40"
},
"2": {
"fajr": "04:15",
"sunrise": "05:42",
"zuhr": "12:30",
"asr": "15:53",
"maghrib": "19:18",
"isha": "20:41"
}
}

解析这个 JSON 字符串所需的 C# 类应该是这样的:

public class 1 {

public string fajr { get; set; }
public string sunrise { get; set; }
public string zuhr { get; set; }
public string asr { get; set; }
public string maghrib { get; set; }
public string isha { get; set; }
}

public class 2 {

public string fajr { get; set; }
public string sunrise { get; set; }
public string zuhr { get; set; }
public string asr { get; set; }
public string maghrib { get; set; }
public string isha { get; set; }
}

但它不能是真正的 C# 类,因为我们知道类名不能以数字开头。

如果有人能建议如何解析这种类型的 json 字符串,那就太好了。

最佳答案

您可以反序列化为字典。

public class Item
{
public string fajr { get; set; }
public string sunrise { get; set; }
public string zuhr { get; set; }
public string asr { get; set; }
public string maghrib { get; set; }
public string isha { get; set; }
}

var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);

关于c# - 如何解析会导致非法 C# 标识符的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24536533/

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