Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - Convert dot notation to JSON

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd start by deserializing it to nested dictionaries.

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

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

        Dictionary<string, object> bottom = dictionary;

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

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

    return dictionary;
}

Once that's done you can use JsonConvert.SerializeObject (from Newtonsoft.Json) to convert the dictionaries to JSON:

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 = JsonConvert.SerializeObject(betterDictionary);

Console.WriteLine(json);

Here's a fiddle with it.

This is the output (formatted):

{
  "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"
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...