Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON to Serialize/Deserialize TimeSpan

I'm trying to deserialize/serialize a timespan with Newtonsoft.Json.JsonConvert, but when the JSON is sent it's set to 00:00:00.

Is this even possible to do?

like image 439
Kevin Avatar asked Jul 12 '10 22:07

Kevin


People also ask

Is JSON deserialization slow?

The expected latency when downloading anything from a server to a client should increase as the size of the file increases.

Is JSON used for serialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

How do you serialize JSON?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.

Why does JSON need to be serialized?

“Serializing” data is used to store and convert complex data types when writing and reading from memory. It is especially useful when sharing data between multiple systems which may not all share common data types.


3 Answers

I tried #Jessycormier's method and it didn't work for me. I ran DataContractJsonSerializer to see what it would generate and I found that gave me a value that looked more like this.

{"PassedTimeSpan":"P1DT2H3M4S"}

The value shown above was for 1 day, 2 hours, 3 minutes, and 4 seconds.

So it looks like format is:

[-]P[{days}D][T[{hours}H][{min}M][{sec}S]]

Where:

- Indicates negative timespan, omitted for positive values
P must be the first character (unless negative time value)
T must precede the time portion of the timespan.
[] = optional part that may be omitted if 0.

like image 172
RonnBlack Avatar answered Oct 09 '22 21:10

RonnBlack


I figured it out, Apparently it's a MS design flaw...

Since TimeSpan cannot be a parameterless object. XML cannot recreate it.

Take a look at this website. http://forums.silverlight.net/forums/p/51793/135450.aspx

So. Therefore TimeSpan cannot be converted. An easy way to do this is to change the timespan into a string, and then send the string over. and use TimeSpan.TryParse(String);

like image 21
Kevin Avatar answered Oct 09 '22 21:10

Kevin


These answers are all outdated, so I thought I would provide an updated better answer. moment.js now directly supports .NET Timespan serialization format.

As of version 2.1.0, this is supported:

moment.duration('23:59:59');
moment.duration('23:59:59.999');
moment.duration('7.23:59:59.999');
moment.duration('23:59'); // added in 2.3.0
like image 32
John Kaster Avatar answered Oct 09 '22 20:10

John Kaster