我正在尝试将模型序列化为Json格式。这是我的模型:
public class UemSiteAvailabilityDetailsRec
{
public string UemAlias;
public string IpAddress;
public DateTimeOffset Date;
public string PlannedOutage;
public string Severity;
public string SiteName;
public string SiteNumber;
public string SourceAgentIp;
public string Message;
}
这是我用来序列化模型实例的代码:
var rec = //GETTING REC FROM DATABASE
var val = JsonNet.Serialize(rec);
然后,我的val
如下所示:
{
"UemAlias": "***.***.**.**",
"IpAddress": "***.***.**.**",
"Date": {
"DateTime": "01\/24\/2019 00:00:21",
"UtcDateTime": "01\/24\/2019 06:00:21",
"LocalDateTime": "01\/24\/2019 00:00:21",
"Date": "01\/24\/2019 00:00:00",
"Day": 24,
"DayOfWeek": 4,
"DayOfYear": 24,
"Hour": 0,
"Millisecond": 800,
"Minute": 0,
"Month": 1,
"Offset": {
"Ticks": -216000000000,
"Days": 0,
"Hours": -6,
"Milliseconds": 0,
"Minutes": 0,
"Seconds": 0,
"TotalDays": -0.25,
"TotalHours": -6,
"TotalMilliseconds": -21600000,
"TotalMinutes": -360,
"TotalSeconds": -21600
},
"Second": 21,
"Ticks": 636838848218000000,
"UtcTicks": 636839064218000000,
"TimeOfDay": {
"Ticks": 218000000,
"Days": 0,
"Hours": 0,
"Milliseconds": 800,
"Minutes": 0,
"Seconds": 21,
"TotalDays": 0.000252314814814815,
"TotalHours": 0.00605555555555556,
"TotalMilliseconds": 21800,
"TotalMinutes": 0.363333333333333,
"TotalSeconds": 21.8
},
"Year": 2019
},
"PlannedOutage": "No",
"Severity": "Critical",
"SiteName": "BA_ISSI",
"SiteNumber": null,
"SourceAgentIp": null,
"Message": "SITE TRUNKING, DEVICE CRITICAL MALFUNCTION"
}
如您所见,我的日期对象看起来里面有很多东西,而不是我需要的东西。然后,当我尝试对字符串进行反序列化时:
var rec = JsonConvert.DeserializeObject<UemSiteAvailabilityDetailsModel>(val);
我收到错误消息...
解析值{时遇到意外字符。路径“日期”, 第1行,位置64。|
如何使序列化功能使DateTimeOffset
的序列化更加简洁并且不会引起错误?
答案 0 :(得分:2)
在我的.Net Core项目中,我无法访问Newtonsoft(据我所知)。
不确定这是否是实现要求,但有适用于.Net Core的Newtonsoft.Json nuget程序包(当前为12.0.1版)。因此,如果您能够重新实现您的解决方案以利用它,则可以通过安装然后使用它来解决问题:
using System;
using Newtonsoft.Json;
namespace ConsoleApp
{
public class Program
{
public class UemSiteAvailabilityDetailsRec
{
public string UemAlias;
public string IpAddress;
public DateTimeOffset Date = new DateTimeOffset(new DateTime(1980, 7, 7));
public string PlannedOutage;
public string Severity;
public string SiteName;
public string SiteNumber;
public string SourceAgentIp;
public string Message;
}
static void Main(string[] args)
{
var toSerialize = new UemSiteAvailabilityDetailsRec();
string val = JsonConvert.SerializeObject(toSerialize);
Console.WriteLine(val);
Console.ReadKey();
}
}
}
这将产生以下json:
{
"UemAlias": "",
"IpAddress": null,
"Date": "1980-07-07T00:00:00-05:00",
"PlannedOutage": null,
"Severity": null,
"SiteName": null,
"SiteNumber": null,
"SourceAgentIp": null,
"Message": null
}