猿问

如何使用日期作为关键 C# 反序列化复杂的 JSON

我正在放弃这个。我有以下需要反序列化的 Json:


json = "{

      "2018-05-21": {

        "lastUpdate": "2018-05-21 01:00:05",

        "stops": [

          {

            "stopId": 1838,

            "stopCode": "02"

    }, {

            "stopId": 1839,

            "stopCode": "08"

    }]}}";


var deserialized = JsonConvert.DeserializeObject<StopDate>(json); // null

和那些类:


public class StopDate

{

    public BusStop date { get; set; }

}

public class BusStop

{

    public string LastUpdate { get; set; }

    public Stop[] Stops { get; set; }

}

public class Stop

{

    public int StopId { get; set; }

    public string StopName { get; set; }

}

问题是反序列化的变量为空。


除了在名称等方面的整体丑陋之外,我希望它能够启动并运行只是为了一个好的开始。感谢所有帮助。


元芳怎么了
浏览 146回答 1
1回答

GCT1015

将 JSON 转换为 Dictionary<DateTime, BusStop>var deserialized = JsonConvert.DeserializeObject<Dictionary<DateTime, BusStop>>(json);DateTime字典的键映射到 JSON 中的日期。如果DateTime导致任何问题,则使用 astring作为密钥,即需要Dictionary<string, BusStop>将密钥解析为 aDateTime的地方var deserialized = JsonConvert.DeserializeObject<Dictionary<string, BusStop>>(json);BusStop busStop = deserialized["2018-05-21"];而且您可能想要制作LastUpdate一个DateTime而不是一个string(如评论者所建议的那样)public class BusStop {&nbsp; &nbsp; public DateTime LastUpdate { get; set; }&nbsp; &nbsp; public Stop[] Stops { get; set; }}public class Stop {&nbsp; &nbsp; public int StopId { get; set; }&nbsp; &nbsp; [JsonProperty("stopCode")]&nbsp; &nbsp; public string StopName { get; set; }}
随时随地看视频慕课网APP
我要回答