The above code looks overly complicated. Working with JSON does not need to be that hard.
To decode the date, I am assuming, form your information above, that your raw JSON data looks something like:
{ "birthday":"2012-03-01T08:00:00" }
This is a known format for the
DataContractJsonSerializer
. To decode, you would use something like this class:
[DataContract]
public class Example
{
[DataMember(Name="birthday")]
public DateTime Birthday { get; set; }
}
The above class was generated using
JsonUtils[
^] website with the above JSON data.
To see this in action, I would use this
Help Class[
^]. It uses
Json.Net[
^]:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Support.CSharp
{
public static class JsonHelper
{
public static string FromClass<T>(T data, bool isEmptyToNull = false,
JsonSerializerSettings jsonSettings = null)
{
string response = string.Empty;
if (!EqualityComparer<T>.Default.Equals(data, default(T)))
response = JsonConvert.SerializeObject(data, jsonSettings);
return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
}
public static T ToClass<T>(string data,
JsonSerializerSettings jsonSettings = null)
{
var response = default(T);
if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject<T>(data)
: JsonConvert.DeserializeObject<T>(data, jsonSettings);
return response;
}
}
}
And to use:
var rawJson = "{ \"birthday\":\"2012-03-01T08:00:00\" }";
var result = JsonHelper.ToClass<Example>(rawJson);
The
Working with JSON in C# & VB[
^] article goes into a lot more detail (with downloadable fully working code) for working with JSON that you should find helpful. :)