I’ve long struggled/grumbled/finagled with .NET’s various stabs at working with JSON data. I think the WCF Web API project has at last come up with a solution that marries the best of JSON with .NET.
dynamic user = new JsonObject();
user.ID = Guid.NewGuid();
user.timeStamp = DateTime.Now;
Console.WriteLine(user.ToString());
Console.ReadLine();
"{\"ID\":\"fea63ed4-52ea-4322-b2f3-1f32061d7306\",\"timeStamp\":\"2011-05-17T11:45:49.000-07:00\"}
Walla -- dynamic .NET typing serialized into JSON.
dynamic ja = new JsonArray
{
new JsonObject
{
{ "ID", new Guid("538a868a-c575-4fc9-9a3e-e1e1e68c70c5") },
{ "Name", "Yavor" },
{ "DOB", new DateTime(1984, 01, 17) },
{ "OrderAmount", 10000 },
{ "IsMarried", false },
{ "OrderHistory", null },
{ "Friends", new JsonArray
{
new Guid("007cf155-7fb4-4070-9d78-ade638df44c7"),
new Guid("91c50a40-7ade-4c37-a88f-3b7e066644dc")
}
}
},
new JsonObject
{
{ "ID", new Guid("007cf155-7fb4-4070-9d78-ade638df44c7") },
{ "Name", "Joe" },
{ "DOB", new DateTimeOffset(1983, 02, 18, 11, 22, 33, TimeSpan.FromHours(0)) },
{ "OrderAmount", 50000 },
{ "Friends", new JsonArray
{
new Guid("91c50a40-7ade-4c37-a88f-3b7e066644dc")
}
}
},
new JsonObject
{
{ "ID", new Guid("91c50a40-7ade-4c37-a88f-3b7e066644dc") },
{ "Name", "Miguel" },
{ "DOB", new DateTimeOffset(1995, 11, 20, 19, 12, 08, TimeSpan.FromHours(-5)) },
{ "OrderAmount", 25300 },
{ "Friends", new JsonArray
{
new Guid("007cf155-7fb4-4070-9d78-ade638df44c7")
}
}
}
};
Console.WriteLine(ja.ToString() + Environment.NewLine);
Console.WriteLine("Get a value");
string name = ja[0].Name;
float orderAmount = ja[0].OrderAmount;
Console.WriteLine("{0}, {1}" + Environment.NewLine, name, orderAmount);
Oh, and if you are grabbing JSON from the wire, you just navigate into the typed JSON. Consider this code, which calls the FourSquare API:
WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);
Console.ReadLine();