【问题标题】:Convert a simple json object to Dictionary List in (C#)将一个简单的 json 对象转换为 (C#) 中的字典列表
【发布时间】:2018-12-14 15:02:19
【问题描述】:

我有一个简单的 json:

{
    "timestamp": "38519277!12/14/2018 08:35:17",
    "entity": "Account",
    "entity": "Contact",
    "entity": "Case"
}

我需要添加到字典中:

Dictionary<string, string> objects = new Dictionary<string, string>();

键是实体,值总是相同的时间戳。我不确定如何进行。这是我以前没有做过的事情。谁能给点建议?

【问题讨论】:

标签: c# .net json


【解决方案1】:

这里...

string json = @"{""timestamp"":""38519277!12/14/2018 08:35:17"",""entity"":""Account""}";

Dictionary<string, string> objects = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

更多详情:

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

【讨论】:

    【解决方案2】:

    如果你想使用字典,唯一的方法就是将值部分作为对象类型或动态。

    Dictionary<string, object> objects = new Dictionary<string, object>();
    

    如果你要使用JsonConvert,那么use this Example

    【讨论】:

      【解决方案3】:

      假设您有一个如下所示的类:

      class Test
      {
          public string timestamp { get; set; }
          public List<string> entity { get; set; }
      }
      

      ...和您的 json 对象看起来像这样(因为正如 cmets 中所指出的,您当前的 json 对象无效)

      "{ \"timestamp\": \"38519277!12 / 14 / 2018 08:35:17\", \"entity\": [\"Account\", \"Contact\", \"Case\"] }"
      

      反序列化var obj = JsonConvert.DeserializeObject&lt;Test&gt;(json);

      这是您想要的代码行:

      Dictionary<string, string> objects = obj.entity.ToDictionary(x => x, x => obj.timestamp);
      

      【讨论】:

        猜你喜欢
        • 2017-12-04
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 2023-03-13
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多