4

How do I setup 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 this kind of structure called in Json. I tried looking for anonymous objects, but didn't have any luck.

2
  • Are you looking for de-serialization into a custom object type, or simply a JSON "DOM"? The DOM is likely much easier, since it wouldn't require any changes to your JSON schema, whereas "serialization" APIs tend to be pickier. Commented Jun 18, 2011 at 20:31
  • DOM would be fine by me. Commented Jun 18, 2011 at 20:41

3 Answers 3

6

This JSON string (or almost, it will be a valid JSON after you fix it and remove the trailing comma, as right now it's invalid) represents an array of arrays of strings. It could be easily deserialized into a string[][] using the built into .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 the exactly same result could be achieved with JSON.NET using the following:

var result = JsonConvert.DeserializeObject<string[][]>(json);
Sign up to request clarification or add additional context in comments.

Comments

5

JSON.Net uses JArray to allow these to be parsed - see:

Comments

0

To see a blog entry detailing how to serialize and deserialize between .NET and JSON, check this out. I found it really helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.