How to deserialize using JSON.NET?

How to configure Newtonsoft Json.net to deserialize this text into a .NET object?

[ [ "US\/Hawaii", "GMT-10:00 - Hawaii" ], [ "US\/Alaska", "GMT-09:00 - Alaska" ], ] 

For bonus points, what is a structure called Json. I tried searching for anonymous objects, but I had no luck.

+4
source share
3 answers

JSON.Net uses JArray to enable their parsing - see:

+5
source

This JSON string (or almost, it will be a valid JSON after correcting it and removing the trailing comma, since it is now invalid) represents an array of string arrays. It can be easily deserialized into string[][] using the built-in .NET JavaScriptSerializer class:

 using System; using System.Web.Script.Serialization; class Program { static void Main() { var json = @"[ [ ""US\/Hawaii"", ""GMT-10:00 - Hawaii"" ], [ ""US\/Alaska"", ""GMT-09:00 - Alaska"" ] ]"; var serializer = new JavaScriptSerializer(); var result = serializer.Deserialize<string[][]>(json); foreach (var item in result) { foreach (var element in item) { Console.WriteLine(element); } } } } 

and exactly the same result can be achieved using JSON.NET using the following:

 var result = JsonConvert.DeserializeObject<string[][]>(json); 
+6
source

To see a blog entry detailing serialization and deserialization between .NET and JSON, check this out . I found this really helpful.

0
source

All Articles