【问题标题】:Deserialize DateTime from a web api从 Web api 反序列化 DateTime
【发布时间】:2018-11-23 20:19:51
【问题描述】:

所以我有一个 sql 数据库,我通过 json API 从其中获取值。 我在反序列化DateTime 变量timeFromtimeTo 时遇到了一些问题。

现在所有的timeFrom 和所有的timeTo 的值都是:

{1/1/0001 上午 12:00:00}

女巫不是正确的值...

这是从 json api 预订房间的一个示例:

{
    "id": "c49af34d-5479-4304-8acc-30f22a7cd1ef",
    "code": 6679,
    "timeFrom": "2018-06-13T16:00:00",
    "timeTo": "2018-06-13T16:45:00",
    "note": null,
    "createdDate": "2018-02-13T10:04:14.8",
    "room": {
      "name": "Rum 1",
      "id": "c49af34d-5479-4304-8acc-30f22a7cd1ef",
      "seats": 10,
      "availableFrom": null,
      "availableTo": null,
      "roomAttributes": [
        {
          "id": 1,
          "name": "Tv",
          "icon": 62060
        },
        {
          "id": 2,
          "name": "Wifi",
          "icon": 61931
        }
      ]
    }
  }

这就是我反序列化 json 的方式:

string booking = "https://api.booknings.com/api/company/c49af34d-5479-4304-8acc-30f22a7cd1ef/room/{room.id}/booking";
HttpClient BookingClient = new HttpClient();
string BookingResponse = await BookingClient.GetStringAsync(booking);
var BookingData = JsonConvert.DeserializeObject<List<Bookings>>(response);

foreach (var books in BookingData)
{
     string note = books.note;
     DateTime TimeFrom = books.timeFrom;
     DateTime TimeTo = books.timeTo;
     Class2 BookRoom = books.room;
     string BookId = books.id;
     int code = books.code;
}

这是我拥有所有预订属性的类:

public class Bookings
{
    public string id { get; set; }
    public int code { get; set; }
    public DateTime timeFrom { get; set; }
    public DateTime timeTo { get; set; }
    public string note { get; set; }
    public DateTime createdDate { get; set; }
    public Class2 room { get; set; }
}

所以我的问题是,是否有人知道我做错了什么......

提前感谢!

【问题讨论】:

  • ...createdDate 被正确序列化了吗?
  • 对我来说很好
  • 我真的不知道。问题是我在这方面唯一需要的是timeFromtimeTo @Schadensbegrenzer
  • @luddep- 你可以使用 newtonsoft.Json
  • 我已经下载了 newtonsoft.Json 但仍然无法正常工作...@Prany

标签: c# json datetime uwp deserialization


【解决方案1】:

你可以使用 Newtonsoft.Json

        var files = JObject.Parse(YourJsonhere);
        var recList = files.SelectTokens("$..timeTo").ToList();
        string value = recList[0].ToString();

【讨论】:

  • Parse 中,我应该粘贴我所有的Json 吗?
  • 是的,请在此处粘贴 json,或者如果文件中有 json,则可以使用流阅读器。像这样 StreamReader sr = new StreamReader(@"C:\pathToJson.json");字符串线 = sr.ReadLine(); var files = JObject.Parse(line);
  • weeelll... 我不认为这是可能的,因为 json 示例只是其中一个房间的所有预订之一,每个房间的所有预订都在一个单独的 URL 扩展中...
  • 您之前是如何计划在现有代码中使用它的。我的意思是使用单个 URL 来捕获?
  • 不,现在我有这个"https://api.bookings.com/api/company/f8b0a9a3-3f87-4c80-bca3-3b6209e7c120/rooms/{room.id}/bookings",所以它需要每个房间的所有预订。
猜你喜欢
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多