c# - 将此 JSON 制作成一个类
问题描述
美好的一天,我似乎无法结束这一点,我想到了这个 JSON 文档,但是作为一个班级,我该怎么做呢?
JSON是这样的:
{
"name": "stacking",
"id": "12345",
"moreDetails" : {
"new_item_0" : {
"id": "abcdefg"
},
"new_item_1" : {
"id": "hujklmn"
},
"new_item_n" : {
"id": "opqrtsu"
}
}
}
其中“moreDetails”中有无限数量的“new_item_n”。
将使用此类作为我在 MongoDB 中的数据库的格式。
我想到的课程是这样的:
public string name;
public string id;
// beyond here I have no idea
解决方案
您可以使用Dictionary<string, class>
:
public partial class Root
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("moreDetails")]
public Dictionary<string, Item> MoreDetails { get; set; }
}
public class Item
{
[JsonProperty("id")]
public string Id { get; set; }
}
所以这:
var x = new Root
{
Name = "stacking",
Id = "1",
MoreDetails = new Dictionary<string, Item> {
{"new_item_0", new Item {Id = "itemId"}}
}
};
JsonConvert.SerializeObject(x, Newtonsoft.Json.Formatting.Indented);
结果是:
{
"name": "stacking",
"id": "1",
"moreDetails": {
"new_item_0": {
"id": "itemId"
}
}
}
推荐阅读
- xcode - AppCenter iOS 设备测试 - 测试运行器无法启动错误
- java - 从字符串列表JAVA中删除连续元素
- php - 如何在使用 Gitlab CI 迁移到服务器之前使用 Composer 安装依赖项
- sql-server - 如何在输出文件中的不同行上获取部分 SSRS 报告数据
- python - 从数组中获取值 - Python
- java - Java 9 中 List/Map 的重载静态工厂方法 - List.of() - 为什么?
- python - 解析 Pandas 数据框列以检查相同的值
- python - 在 Python 中重现 R 的高斯过程最大似然回归
- python - 打印出具有最大/最佳 AUC 分数的最佳参数
- asp.net-mvc-5 - MVC 6 和 ADFS 身份验证