0

How do i convert dot notation to json
The dot notation can have any depth

All data is current like this:

Dictionary<string, string> data = new Dictionary<string, string>
{
    {"Company.Website", "Hjemmeside"},
    {"Company.TextHeaderPlaceholder", "Firmanavn"},
    {"Company.User.Manager.Repositories.CreateAsync.ArgumentNullException.InvalidCompanyId", "firma id fejl"},
    {"BookingSettings.HelpText", "Hjælpe tekst på webshop"},
    {"BookingSettings.OnGoingOrderValidation.Text", "Bestillings validering i gang"},
    {"BookingSettings.OnGoingOrderValidation.Created", "Oprettet"},
    {"BookingSettings.Url", "Kundelink til booking"}
};

Json result should be:

{
  "Company": {
    "Website": "Hjemmeside",
    "TextHeaderPlaceholder": "Firmanavn",
    "Users": {
      "Managers": {
        "Repositories": {
          "CreateAsync": {
            "ArgumentNullException": {
              "InvalidCompanyId": "Can not create company user with out a company!"
            }
          }
        }
      }
    }
  },
  "BookingSettings": {
    "HelpText": "Hjælpe tekst på webshop",
    "OnGoingOrderValidation": {
      "Text": "Bestillings validering i gang",
      "Created": "Oprettet"
    },
    "URL": "Kundelink til booking"
  }
}

How do this the easy way?

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
  • 1
    What had you tried so far? what about `string.Split` ? also it doesn't looks like `Dictionary` ... rather `Dictionary` where `object` can be either `string` or `Dictionary` – Selvin Mar 12 '19 at 09:58
  • Looks to me like simply a class instance with members that have certain values. Have you tried simply serialising the `Company` object to JSON? – LocEngineer Mar 12 '19 at 10:04
  • Try to clearify what am trying to do, I have working with Home.Somthing just recurcive down any depth –  Mar 12 '19 at 10:23
  • it can be done with 1 line [...](https://dotnetfiddle.net/93wC6X) and of course "BookingSettings.Url" doesn't exists ... – Selvin Mar 12 '19 at 10:30
  • @Selvin I wrote a [solution](https://stackoverflow.com/a/55119898/1275774) like the one you suggested. It's been a while since I did magic LINQ-to-JSON (with Newtonsoft.Json) but that's something that probably could be used. Else a custom `JsonConverter`. – Mikael Dúi Bolinder Mar 12 '19 at 11:57
  • I didn't get the question properly from first question's version :) and solution from my comment is a opposite to the stuff that OP wanted – Selvin Mar 12 '19 at 12:01

1 Answers1

10

I'd start by deserializing it to nested dictionaries.

public static Dictionary<string, object> DotNotationToDictionary(Dictionary<string, string> dotNotation)
{
    Dictionary<string, object> root = new Dictionary<string, object>();

    foreach (var dotObject in dotNotation)
    {
        var hierarcy = dotObject.Key.Split('.');

        Dictionary<string, object> current = root;

        for (int i = 0; i < hierarcy.Length; i++)
        {
            var key = hierarcy[i];

            if (i == hierarcy.Length - 1) // Last key
            {
                current.Add(key, dotObject.Value);
            }
            else 
            {
                if (!current.ContainsKey(key))
                    current.Add(key, new Dictionary<string, object>());
                
                current = (Dictionary<string, object>) current[key];
            }
        }
    }

    return root;
}

Once that's done you can use JsonSerializer.Serialize to convert the dictionaries to JSON (JavaScriptEncoder.UnsafeRelaxedJsonEscaping needed for "æ"):

Dictionary<string, string> dotNotation = new Dictionary<string, string>
{
    {"Company.Website", "Hjemmeside"},
    {"Company.TextHeaderPlaceholder", "Firmanavn"},
    {"Company.User.Manager.Repositories.CreateAsync.ArgumentNullException.InvalidCompanyId", "firma id fejl"},
    {"BookingSettings.HelpText", "Hjælpe tekst på webshop"},
    {"BookingSettings.OnGoingOrderValidation.Text", "Bestillings validering i gang"},
    {"BookingSettings.OnGoingOrderValidation.Created", "Oprettet"},
    {"BookingSettings.Url", "Kundelink til booking"}
};

var betterDictionary = DotNotationToDictionary(dotNotation);

var json = JsonSerializer.Serialize(betterDictionary, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });

Console.WriteLine(json);

Here's a fiddle with it.

This is the output:

{
  "Company": {
    "Website": "Hjemmeside",
    "TextHeaderPlaceholder": "Firmanavn",
    "User": {
      "Manager": {
        "Repositories": {
          "CreateAsync": {
            "ArgumentNullException": {
              "InvalidCompanyId": "firma id fejl"
            }
          }
        }
      }
    }
  },
  "BookingSettings": {
    "HelpText": "Hjælpe tekst på webshop",
    "OnGoingOrderValidation": {
      "Text": "Bestillings validering i gang",
      "Created": "Oprettet"
    },
    "Url": "Kundelink til booking"
  }
}
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44