简体   繁体   中英

Can't parse JSON data to .NET DateTime

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!

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

        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)\\/\"";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM