Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize with JSON.NET?

Tags:

json

c#

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.

like image 651
Jake Pearson Avatar asked Dec 21 '22 12:12

Jake Pearson


1 Answers

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);
like image 99
Darin Dimitrov Avatar answered Jan 05 '23 09:01

Darin Dimitrov