【问题标题】:JsonConvert.DeserializeObject for json with different key names [duplicate]具有不同键名的 json 的 JsonConvert.DeserializeObject [重复]
【发布时间】:2017-06-19 20:45:43
【问题描述】:

我正在尝试为这个奇怪的 json 使用 Json.Net 转换器:

{
  "Key1": {
  "id": "1",
  "name": "one"
  },
  "Key2": {
  "id": "2",
  "name": "two"
  },
...
  "CouldBeAnything": {
  "id": "n",
  "name": "CouldBeAnything"
  }
}

如果我使用 json 到 xml 源生成,我会得到具有名为 Key1、Key2 等属性的对象。这不起作用,因为我需要与它们关联的那些键和值的列表。有没有办法创建一个可以直接序列化的对象?提前致谢。

【问题讨论】:

  • 使用Dictionary<string, MyValueClass> 解释herehere
  • 非常感谢!!

标签: c# json json.net


【解决方案1】:

你可以这样做:

    class Class1
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    static void Main(string[] args)
    {
        var d = new Dictionary<string, Class1>();

        d.Add("Key1", new Class1() { id = "1", name = "one" });
        d.Add("Key2", new Class1() { id = "2", name = "two" });
        d.Add("CouldBeAnything", new Class1() { id = "n", name = "CouldBeAnything" });

        var json = JsonConvert.SerializeObject(d, Formatting.Indented);

    }

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2018-11-06
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多