Reputation: 49599
For a strange reason that does not matter for this question I need to create a JSON compatible substring that represents a DateTime and that will be manually insterted into a larger JSON string that later will be parsed by .NET's DataContractJsonSerializer. I have come up with the following method:
static readonly DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(DateTime));
private static string ToJsonString(DateTime time)
{
using (var memStream = new MemoryStream())
{
s.WriteObject(memStream, time);
return Encoding.UTF8.GetString(memStream.ToArray());
}
}
Is there any simpler way to do this or can the code above be optimized in any way? Or is there even a mistake in the code above?
Also it would be really cool if I could do it without the use of DataContractJsonSerializer since the string building will also be done in a pure .NET 1.1 process.
Upvotes: 4
Views: 1225
Reputation: 251
I would use NewtonSoft JSON and delegate the responsibility of serializing the DateTime to that. It supports serializing DateTime to ISO 8601 format (2008-04-12T12:53Z etc) and is far more reliable than DataContractJsonSerializer.
You can use it to serialize native objects or use it as a text writer to manually generate JSON. It's easier to use this than writing strings out believe me.
Alternatively, you could wrap that inside your ToString logic.
Upvotes: 1
Reputation: 166
Could you use the milliseconds-from-epoch time approach? Like this extension method?
public static class DateTimeExtensions
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1);
public static string ToJson(this DateTime time)
{
return string.Format("\\/{0:0}\\/", (time - Epoch).TotalMilliseconds);
}
}
Upvotes: 1