问题描述
我目前正在构建一个项目,用于检索 API 数据并将其保存到数据库中。除了 API 中的 DateTime 值外,一切正常。我有一个使用 RestSharp 获取 API 数据的类,然后它使用 NewtonSoft.Json 将 API 数据反序列化为 JSON 格式,然后将其存储到临时 DTO 类文件中。这是 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);
}
}
现在是临时存储转换后的 JSON 数据的 DTO 文件 (AllRequests)。
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; }
}
}
我希望成为日期时间格式的详细信息中的代码行是“DueByTime”和“CreatedTime”,而不是字符串值。目前,他们只在字符串中保存 JSON 格式的 DateTime 值,例如“1477394860065”。
我已经尝试将 "public string CreatedTime { get; set; }" 设置为 "public DateTime CreatedTime { get; set; }" 但是这只返回了一个错误,因为它是 JSON 格式。我怎样才能纠正这个问题,以便它以 DateTime 格式正确存储在 DTO 中?因为理想情况下我想将这个类文件构建到一个表中,以便它可以在数据库中保存数据。
有关这方面的更多背景信息,这是我想要在我的数据库中纠正的内容。
我希望显示一个 DateTime,而不是像 Createby 和 DueBy 下的一长串数字。
任何帮助将不胜感激。
解决方法
[EDIT] 添加了 Unix 时间格式合规性[/EDIT]
只需输入@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);
}
}
还使用 this answer 按照要求转换为 DateTime,使用本地时间。
如果您不需要偏移量,以下是转换为 DateTime 的方法:https://docs.microsoft.com/fr-fr/dotnet/standard/datetime/converting-between-datetime-and-offset