Bizmark
Bizmark

Reputation: 131

Deserializing a JSON string formatted as a dictionary

Using C# (.Net 4.6) and JSON.NET

I'm currently trying to deserialize a large JSON string that has been presented in a format with multiple levels - I'm aiming to store some of this data in a flat DB table, going via a C# class to build the data in the required format that will be written back to each row.

Here's an example of the string format (made up data with line breaks added to increase readability):

{
    "Microsoft":
    {
        "name" : "Microsoft",
        "products" : ["Word", "Excel", ["TestThis","TestOrThis"]],
        "employees" : 
        [
            {"John" :{"name" :  "John","skills" : ["Support", "Programming"]}}, 
            {"Dave":{"name" :  "Dave", "skills" : ["Tester"]}}
        ]
    }
}

What I really want to end up with is a database row that has just some of this information, reading something like:

"Company Name", "Employee Name" 

e.g.

"Microsoft", "John"
"Microsoft", "Dave"
"IBM", "Ted"

Reading a basic JSON string is easy enough, however I'm new to using JSON which has left me stumped on how to break this down.

Upvotes: 0

Views: 87

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129807

We can deserialize your JSON by first defining a couple of classes like this:

class Company
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("employees")]
    public List<Dictionary<string, Employee>> Employees { get; set; }
}

class Employee
{
    [JsonProperty("name")]
    public string Name { get; set; }
}

Then we can deserialize into a Dictionary<string, Company> like this:

var companies = JsonConvert.DeserializeObject<Dictionary<string, Company>>(json);

You'll notice that wherever the keys can vary in the JSON (e.g. the company and employee names), we need to use a Dictionary in place of a static class. Also, we can omit defining properties for the items we are not interested in, like products and skills.

Once we have the deserialized companies, we can loop through the results to arrive at the desired output like this:

foreach(KeyValuePair<string, Company> kvp in companies)
{
    foreach (Dictionary<string, Employee> employees in kvp.Value.Employees)
    {
        foreach (KeyValuePair<string, Employee> kvp2 in employees)
        {
            Console.WriteLine(kvp.Value.Name + ", " + kvp2.Value.Name);
        }
    }
}

Output:

Microsoft, John
Microsoft, Dave

Fiddle: https://dotnetfiddle.net/FpK7AN

Upvotes: 1

BWA
BWA

Reputation: 5764

On site json2csharp.com generete classes from your JSON, your example isn't valid JSON. And deserialize your JSON into generated classes. Sometimes tool generates bad classes, so be carefull.

Upvotes: 0

Related Questions