Can't parse JSON data to .NET DateTime

瘦欲@ 提交于 2019-12-25 09:24:37

问题


It's pretty simple. I have a string

string s = "/Date(1474408920000)/"

And I want to convert it to a date:

DateTime date = JsonConvert.DeserializeObject<DateTime>(s);

But I get the error:

"Error parsing comment. Expected: *, got D. Path '', line 1, position 1."

What's going on here?

Thanks for your help!


回答1:


Your json string is not valid but can easily be fixed by surrounding it with "

string s = @"""/Date(1474408920000)/""";

Now DateTime date = JsonConvert.DeserializeObject<DateTime>(s); will work




回答2:


        var LogDate = new DateTime(2016, 9, 20, 22, 2, 0, DateTimeKind.Utc);

        string JsonDate = JsonConvert.SerializeObject(LogDate, new JsonSerializerSettings {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        });

        Console.WriteLine(JsonDate);
        Console.ReadLine();

Output from this code gives you a proper JSON date format:

"\/Date(1474408920000)\/"

So your string should look like this:

string s = "\"\\/Date(1474408920000)\\/\"";



回答3:


try serializing the DateTime obj to JSON using below code.

        var dateTime = DateTime.Now;
        var jsonDate = Newtonsoft.Json.JsonConvert.SerializeObject(dateTime, 
                            new Newtonsoft.Json.JsonSerializerSettings() { 
                                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat, 
                                DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime });

jsonDate would hold this value "\"\\/Date(1474408920000)\\/\"" or something in this format.
Now deserialize your json date string using below code.

var dateObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(dateString, 
                            new Newtonsoft.Json.JsonSerializerSettings() { 
                                DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime, 
                                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat });


来源:https://stackoverflow.com/questions/39669511/cant-parse-json-data-to-net-datetime

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