如何解析会导致非法 C# 标识符的 JSON 字符串? [英] How can I parse a JSON string that would cause illegal C# identifiers?
问题描述
我一直在使用 NewtonSoft JSON Convert 库来解析 JSON 字符串并将其转换为 C# 对象.但是现在我遇到了一个非常尴尬的 JSON 字符串,我无法将它转换为 C# 对象,因为我无法从这个 JSON 字符串中创建一个 C# 类.
I have been using NewtonSoft JSON Convert library to parse and convert JSON string to C# objects. But now I have came across a really awkward JSON string and I am unable to convert it into C# object because I cant make a C# class out of this JSON string.
这里是 JSON 字符串
Here is the JSON string
{
"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# 类应该是这样的:
The C# class required to parse this JSON string should be like this:
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# 类,因为我们知道类名不能以数字开头.
But it cant be a true C# class because we know that Class names cannot start with a number.
如果有人能建议如何解析这种类型的 json 字符串,那就太好了.
It will be really great if anyone can suggest how to parse such type of json string.
推荐答案
您可以反序列化为字典.
You can deserialize to a dictionary.
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# 标识符的 JSON 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!