首页 > 解决方案 > 将此 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

标签: c#json

解决方案


您可以使用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"
    }
  }
}

推荐阅读