Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - JsonConvert.DeserializeObject could not convert string to DateTime when using non-us date formats

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

And Im hitting an error:

"Could not convert string to DateTime: 13/02/2014. Path 'DeliveryDate', line 1, position 323."

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...