简体   繁体   English

JToken.Parse与SerializeObject中的日期处理

[英]Date handling in JToken.Parse vs SerializeObject

I'm wondering if anyone has seen this "issue" before and potential solutions on how to correct it? 我想知道是否有人曾经看过这个“问题”以及如何纠正它的潜在解决方案?

I have a specific date format (MicrosoftDateFormat) that needs to be used when talking to an SAP Gateway service for DateTime fields. 与DateTime字段的SAP Gateway服务进行对话时,需要使用一种特定的日期格式(MicrosoftDateFormat)。

This code: 这段代码:

string payload = JsonConvert.SerializeObject(myObject, new JsonSerializerSettings()
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

serializes the DateTime fields into the required formats, eg: 将DateTime字段序列化为所需的格式,例如:

"DocumentModifiedDate": "/Date(1533686400000)/"

But I then need to transform the JSON to a JToken object in order to pass it through the framework to my web service. 但是我随后需要将JSON转换为JToken对象,以将其通过框架传递给我的Web服务。 When I transform to a JToken, the date is formatted back to the ATOM style approach: 当我转换为JToken时,日期被格式化为ATOM样式方法:

var jot = Newtonsoft.Json.Linq.JToken.Parse(payload); 

Which results in: 结果是:

"DocumentModifiedDate": "2018-08-08T00:00:00Z"

I've tried using the JToken.FromObject approach: 我尝试使用JToken.FromObject方法:

var jot = Newtonsoft.Json.Linq.JToken.FromObject(myObject, new JsonSerializer()
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

But this doesn't seem to make use of the of serializer settings. 但这似乎并未利用序列化程序设置。

Hopefully someone has encountered this before and can assist. 希望有人曾经遇到过这种情况,可以为您提供帮助。

If you can't assist here, then is there an easy way to perform that conversion in node.js because there is a chance to do it on the web server side before actually sending it off to SAP. 如果您在这里不能提供帮助,那么有一种简便的方法可以在node.js中执行该转换,因为在实际将其发送给SAP之前,有机会在Web服务器端进行转换。 I'm not wanting to add too much complexity to the web side of the equation so if I can do it on the app side, it'd be a lot more preferrable. 我不想在方程式的网络端增加太多复杂性,因此,如果我可以在应用程序端做到这一点,那就更可取了。

I got the answer via a more roundabout method, which is probably correct, I'm not sure. 我通过更round回的方法得到了答案,这可能是正确的,我不确定。 bottom line is, it works. 最重要的是,它有效。

Something like this ... 像这样的东西...

var payload = JsonConvert.SerializeObject(myObject, new JsonSerializerSettings()
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

using (var sr = new StringReader(payload))
using (var jr = new JsonTextReader(sr) { DateParseHandling = DateParseHandling.None })
{
    var jot = JToken.ReadFrom(jr);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM