使用非美国日期格式时

使用非美国日期格式时

本文介绍了使用非美国日期格式时,JsonConvert.DeserializeObject无法将字符串转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下序列化的json对象:

I have the following serialized json object:

"{\"LineItems\":[{\"LineID\":1,\"QuoteID\":\"00000000-0000-0000-0000-000000000000\",\"Quantity\":\"1\",\"UnitPriceExTax\":\"2\",\"UnitPriceTaxRate\":\"2\",\"UnitPriceTaxAmt\":0,\"LineTotalExTax\":2,\"LineTotalTaxAmt\":0.040000000000000036,\"LineTotalIncTax\":2.04}],\"QuoteID\":[],\"CurrencyID\":\"2\",\"SupplierRef\":\"SDFSFSDF\",\"DeliveryDate\":\"22/02/2014\",\"QuoteAvailablityStartDate\":\"13/02/2014\",\"QuoteAvailablityEndDate\":\"09/02/2014\",\"OpeningComments\":\"WWSFSFS \",\"PricingComments\":\"XSDFSDF \",\"DeliveryComments\":\"SDFSFSDF SDFSFSF\",\"TermsComments\":\"SFSFSDF SDFSFSDF SDFS\",\"FreightExTax\":\"1\",\"FreightExTax2\":1,\"FreightTaxRate\":\"1\",\"FreightTaxAmt\":0.010000000000000009,\"FreightIncTax\":1.01,\"TotalLinesExTax\":2,\"TotalLinesTaxAmt\":0.040000000000000036,\"TotalExTax\":3,\"TotalTaxAmt\":0.050000000000000044,\"TotalIncTax\":3.05}"

将其中一个发送到我要反序列化的服务器,如下所示:

One this is sent to the server I am trying to deserialize as follows:

var json = Request.RequestContext.HttpContext.Request.Params["EoiDraftModel"];
var ld = JsonConvert.DeserializeObject<EoiDraftViewModel>(json);

然后我遇到错误:

由于日期是有效的,所以我假设它是非美国格式的问题.实际上,我知道这是因为如果我一天的工作量少于13,那么反序列化就可以了.那么,如何指示反序列化器使用非美国日期?

Since the date is valid I'm assuming its a problem with non-us format. In fact I know it is because if I do less than 13 for my days it deserializes just fine. So how do I indicate to deserializer to use non-us dates?

推荐答案

尝试专门使用IsoDateTimeConverter指定DateTime格式,并将其传递给JsonConvert.DeserializeObject<>()方法.

Try specifying the DateTime format specifically using an IsoDateTimeConverter, and pass it into the JsonConvert.DeserializeObject<>() method.

...
var json = Request.RequestContext.HttpContext.Request.Params["EoiDraftModel"];

var format = "dd/MM/yyyy"; // your datetime format
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format };

var ld = JsonConvert.DeserializeObject<EoiDraftViewModel>(json, dateTimeConverter);
...

这篇关于使用非美国日期格式时,JsonConvert.DeserializeObject无法将字符串转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:18