首页 > 解决方案 > JSON 转换为 C#

问题描述

任何人都知道如何将此 JSON POSTMAN JSON 图像转换为 C# 类,我想创建一个字典,其中键为日期,值与其他属性。在线工具将其转换为在线工具转换器 JSON 到 C#,但这是不对的。

这是我的 JSON:

{
    "2020-08-27": [
        {
            "Duration": 424,
            "End": "13:04",
            "Start": "06:00"
        },
        {
            "Duration": 366,
            "End": "20:00",
            "Start": "13:54"
        }
    ],
    "2020-08-28": [
        {
            "Duration": 427,
            "End": "13:07",
            "Start": "06:00"
        },
        {
            "Duration": 159,
            "End": "20:00",
            "Start": "17:21"
        }
    ],
    "2020-08-31": [
        {
            "Duration": 15,
            "End": "06:15",
            "Start": "06:00"
        },
        {
            "Duration": 111,
            "End": "08:40",
            "Start": "06:49"
        },
        {
            "Duration": 630,
            "End": "20:00",
            "Start": "09:30"
        }
    ]
}

标签: c#json

解决方案


您有一个符合 aDateTime和 a的 Dictionary 的 json List<Item>。您可以使用以下内容来反序列化您的 Json

public class Item
{
    public int Duration { get; set; }
    public string End { get; set; }
    public string Start { get; set; }
}

// and in main,
var obj = JsonConvert.DeserializeObject<Dictionary<DateTime, List<Item>>>(json);

// Use TryGetValue to look up values of a specific Key 
obj.TryGetValue(DateTime.Parse("8/27/2020"), out List<Item> items);
Console.WriteLine(string.Join(", ", items.Select(x => x.Duration)));

// prints
424, 366

推荐阅读