使用非美国日期格式时,JsonConvert.DeserializeObject无法将字符串转换为DateTime

时间:2014-02-13 02:35:23

标签: c# javascript json json.net

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

"{\"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}"

将其发送到我尝试反序列化的服务器,如下所示:

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

我遇到了一个错误:

  

“无法将字符串转换为DateTime:13/02/2014。路径   'DeliveryDate',第1行,第323位。“

由于日期有效,我假设它与非美国格式存在问题。事实上,我知道这是因为如果我的日子少于13,那么反序列化就好了。那么我如何指示反序列化器使用非美国日期?

1 个答案:

答案 0 :(得分:46)

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

...
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);
...