我该如何解析JSON字符串,将导致非法C#标识符? [英] How can I parse a JSON string that would cause illegal C# identifiers?
问题描述
我一直在使用 NewtonSoft JSON转换库来解析和JSON字符串转换为C#对象。但现在我已经跨越好不尴尬JSON字符串来了,我无法把它转换成C#对象,因为我不能让一个C#类出这个JSON字符串的。
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字符串
{
"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);
这篇关于我该如何解析JSON字符串,将导致非法C#标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!