C# 反序列化包含datetime属性的多列JSON对象
在一个C#项目中,我正在检索一个事件对象,其中包含subject(字符串)、location(字符串)、start_time(datetime)、end_time(datetime)、all_day_事件(布尔值)和calendar_id(int)属性,作为Rest请求的JSON响应。该请求从数据库获取数据,并且该数据库上的开始时间和结束时间列的类型也是datetime。但是我在获取日期时间类型值方面遇到了麻烦。我得到的JSON对象如下:C# 反序列化包含datetime属性的多列JSON对象,c#,json,datetime,json.net,C#,Json,Datetime,Json.net,在一个C#项目中,我正在检索一个事件对象,其中包含subject(字符串)、location(字符串)、start_time(datetime)、end_time(datetime)、all_day_事件(布尔值)和calendar_id(int)属性,作为Rest请求的JSON响应。该请求从数据库获取数据,并且该数据库上的开始时间和结束时间列的类型也是datetime。但是我在获取日期时间类型值方面遇到了麻烦。我得到的JSON对象如下: [ { "id": 1, "subj
[
{
"id": 1,
"subject": "Test Event 1",
"location": "Test Location",
"start_time": "2019-08-22 10:17:53",
"end_time": "2019-08-22 10:17:55",
"all_day_event": 0,
"calendar_id": 1
}
]
这是我的活动课:
public class Event {
public int Id { get; set; }
public string Subject { get; set; }
public string Location { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool AllDayEvent { get; set; }
public int CalendarId { get; set; }
}
这就是我反序列化JSON对象的方式:
events = JsonConvert.DeserializeObject<Event[]>(response.Content);
events=JsonConvert.DeserializeObject(response.Content);
当我直接打印JSON对象时,它会正确显示。但是在我反序列化它之后,时间值显示为01/01/0001 12:00 AM。我找了好一阵子了。我已经找到了一些建议,但没有任何帮助。那么,有没有办法正确获得这些时间值??非常感谢。正如Aleks所说,您需要装饰具有不同命名约定的房产。请记住,Json.Net将自动将Json的snakeCase映射到C#的PascalCase属性中。然而,如果你有蛇皮盒或其他东西,你需要装饰属性
public class Event
{
public int Id { get; set; }
public string Subject { get; set; }
public string Location { get; set; }
[JsonProperty("start_time")]
public DateTime StartTime { get; set; }
[JsonProperty("end_time")]
public DateTime EndTime { get; set; }
[JsonProperty("all_day_event")]
public bool AllDayEvent { get; set; }
[JsonProperty("calendar_id")]
public int CalendarId { get; set; }
}
此外,您可以设置全局命名策略,以避免装饰模型的所有属性,如果JSON遵循snake_case for,则需要将
[JsonProperty(“start_time”)]
属性应用于StartTime
property@OğuzÖztınaz检查文档示例,也许你最好使用SnakeCaseNamingStrategy,而不是装饰你可能拥有的所有模型