[英]Unsure how to define a C# class to handle JSON with variable property names
I am calling a REST api that returns their data in the following format: 我正在调用一个REST API,以以下格式返回其数据:
{
"facets": [
{
"M": 100
},
{
"F": 210
}
]
}
I am not sure how to define a C# class that maps to this JSON since the M/F property name could be anything. 我不确定如何定义映射到此JSON的C#类,因为M / F属性名称可以是任何东西。 This is currently a facet for gender, but for something else like language it might be "English", "Spanish", "Japanese", etc. Ideally I would like something like a dictionary.
目前这是性别的一个方面,但是对于其他语言(例如语言),可能是“英语”,“西班牙语”,“日语”等。理想情况下,我希望使用字典。
Where the keys can vary, use a dictionary to represent the object: 键可以变化的地方,使用字典来表示对象:
public class Criteria
{
public List<Dictionary<string, int>> facets { get; set; }
}
(If the dictionary value isn't always an int
, use object
instead.) (如果字典值不总是
int
,则使用object
。)
Fiddle: https://dotnetfiddle.net/IwyXby 小提琴: https : //dotnetfiddle.net/IwyXby
This is how I use json.net to both serialize and deserialize: 这就是我使用json.net进行序列化和反序列化的方式:
public static bool SerializeStudentsFile(string fileStorageLoc)
{
var jsonStudents = JsonConvert.SerializeObject(StudentsList);
System.IO.File.WriteAllText(fileStorageLoc, jsonStudents);
return true;
}
public static List<Student> DeserializeStudentsFile()
{
List<Student> studentList;
if (!System.IO.File.Exists(STUDENTS_FILENAME))
{
var studentFile = System.IO.File.Create(STUDENTS_FILENAME);
studentFile.Close();
}
var studentContentsFile = System.IO.File.ReadAllText(STUDENTS_FILENAME);
var studentContentsFileDeserialized = JsonConvert.DeserializeObject<List<Student>>(studentContentsFile);
if (null != studentContentsFileDeserialized) return studentContentsFileDeserialized;
studentList = new List<Student>();
return studentList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.