Jake Pearson
Jake Pearson

Reputation: 27757

How to deserialize with JSON.NET?

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.

Upvotes: 4

Views: 9671

Answers (3)

RobinDotNet
RobinDotNet

Reputation: 11877

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

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);

Upvotes: 6

Stuart
Stuart

Reputation: 66882

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

Upvotes: 5

Related Questions