JsonConvert.SerializeObject vs JsonSerializer.Serialize

时光总嘲笑我的痴心妄想 提交于 2019-12-21 05:03:06

问题


Alright I can't figure out why JsonConvert.SerializeObject serializes DateTime objects differently than JsonSerializer.Serialize.

Given the class

public class Test
{
     [JsonConverter(typeof(JavaScriptDateTimeConverter))]
     public DateTime DeliveryDate { get { return DateTime.Now; } }
}

@Html.Raw(JsonConvert.SerializeObject(new Test()))

outputs:

"DeliveryDate": "2013-03-01T07:00:00.000Z"

but when I use JsonSerializer.Serialize like in JsonNetResult: http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

I get the following output:

"DeliveryDate": new Date(1362520794703)

I can't figure out why there is this inconsistency. I would had thought JsonConvert.SerializeObject would use JsonSerializer internally.


回答1:


Alright I've figured it out and I want to share in case anyone ever comes across this scenario.

So a long time ago I was having trouble serializing DateTime objects the JsonResult in MVC4. Basically my DateTime objects were being serialized to "\/Date(1239018869048)\/" I think I read an answer from the author for JSON.NET on SO recommending to add [JsonConverter(typeof(JavaScriptDateTimeConverter))] to the DateTime properties of the model class and using @Html.Raw(JsonConvert.SerializeObject(Model) in the View. So sure enough I did that and that fixed my short term problem at the time

Time goes by and today I need to support updating the javascript viewModel on the fly after the user posts some stuff to the server. Which brings up my error today. Well it turns out that ALL my DateTime properties were decorated with the attribute and when I tried to serialize them back down to the client the serializer WAS behaving like as expected. Which lead me believing the JsonConvert.SerializeObject was in fact NOT respecting the attributes.

After I removed the offending attributes everything started to work fantastic. Tweaking things around I found I can just use default DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind and I can forget about the Z in my date time strings.



来源:https://stackoverflow.com/questions/15235042/jsonconvert-serializeobject-vs-jsonserializer-serialize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!