[英]How do I convert a JSON DateTime format to a C# DateTime format from an API call
我目前正在构建一个项目,该项目检索 API 数据并将其保存到数据库中。 除了 API 中的 DateTime 值外,一切正常。 I have a class that uses RestSharp to obtain the API data then it uses NewtonSoft.Json to derserialize the API data into a JSON format which is then stored into a temporary DTO class file. 这里是 API 方法。
public static void getAllRequestData()
{
var client = new RestClient("[My API URL]");
var request = new RestRequest();
var response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string rawResponse = response.Content;
AllRequests.Rootobject result = JsonConvert.DeserializeObject<AllRequests.Rootobject>(rawResponse);
}
}
现在这里是 DTO 文件 (AllRequests),它将临时存储转换后的 JSON 数据。
public class AllRequests
{
public class Rootobject
{
public Operation Operation { get; set; }
}
public class Operation
{
public Result Result { get; set; }
public Detail[] Details { get; set; }
}
public class Result
{
public string Message { get; set; }
public string Status { get; set; }
}
public class Detail
{
[Key]
public int Id { get; set; }
public string Requester { get; set; }
public string WorkOrderId { get; set; }
public string AccountName { get; set; }
public string CreatedBy { get; set; }
public string Subject { get; set; }
public string Technician { get; set; }
public string IsOverDue { get; set; }
public string DueByTime { get; set; }
public string Priority { get; set; }
public string CreatedTime { get; set; }
public string IgnoreRequest { get; set; }
public string Status { get; set; }
}
}
我希望成为 DateTime 格式的详细信息中的代码行是“DueByTime”和“CreatedTime”,而不是字符串值。 目前他们只在字符串中保存 JSON 格式的 DateTime 值,例如“1477394860065”。
我尝试将“ public string CreatedTime { get; set; } ”设置为“ public DateTime CreatedTime { get; set; } ”但是由于它是 JSON 格式,因此只返回了一个错误。 我怎样才能纠正这个问题,以便它以 DateTime 格式正确存储在 DTO 中? 因为理想情况下我想将这个 class 文件搭建到一个表中,这样它就可以在数据库中保存数据。
有关这方面的更多背景信息,这是我想在我的数据库中纠正的内容。
我希望显示一个 DateTime,而不是像 Createby 和 DueBy 下的一长串数字。
任何帮助,将不胜感激。
[编辑] 添加了 unix 时间格式合规性[/编辑]
只需输入@Fildor 所说的代码
public long CreatedTime { get; set; }
[JsonIgnore] // will ignore the property below when serializing/deserializing
public DateTimeOffset CreatedTimeDate {
// Don't need a setter as the value is directly get from CreatedTime property
get {
return DateTimeOffset.FromUnixTimeMilliseconds(CreatedTime);
}
}
还使用此答案使用本地时间按要求转换为 DateTime。
如果不需要偏移量,以下是转换为 DateTime 的方法: https://docs.microsoft.com/fr-fr/dotnet/standard/datetime/converting-between-datetime-and-offset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.