0

I have a horrible DB structure with no naming convention and table and field names are all over the place. I need to present some of this data to a freshly developed mobile app, and I would like to at least present a "clean" design to the mobile app regarding the table and field names.

To this end, I am writing code that will create "nice" json objects for the mobile app to consume. I don't want to manually go and make the "right" name for each field in my db, I would like an automated process to do this.

So the rule I'm trying to apply is: All table and field names should be in lowerCamelCase.

e.g.

Apple_Cart => appleCart
AppleCart => appleCart
Apple__Cart => appleCart
appleCart => appleCart
APPLE_CART => appleCart
Apple_Cart => appleCart
APPLECart => appleCart  (not sure about this one)

I dont want to reinvent the wheel here, and I'm sure that either Newtonsoft.Json or another library already has code to do this? Please can someone show me a good way to go about converting field and table name strings to json standard format.

This is how far I got before deciding that I'm about to reinvent the wheel..

    /// <summary>
    /// Makes the json identifier.
    /// </summary>
    /// <param name="fieldName">Name of the field.</param>
    /// <returns></returns>
    private string MakeJsonIdentifier(string fieldName)
    {
        StringBuilder sb = new StringBuilder(fieldName);
        while (sb.ToString().Contains("_"))
        {
            int posOfFirstUs = sb.ToString().IndexOf("_", StringComparison.Ordinal);
            if (sb.ToString().Length > posOfFirstUs + 1)
            {
                sb[posOfFirstUs + 1] = char.ToUpperInvariant(sb.ToString()[posOfFirstUs + 1]);
                sb.Remove(posOfFirstUs, 1);
            }
        }
        return sb.ToString();
    }
user230910
  • 2,353
  • 2
  • 28
  • 50

1 Answers1

1

You can use this function to get lowerCamelCase, i use it also and it work great.

Source code

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
    return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
  }).replace(/\s+/g, '');
}

C# You can use this method but you have to set separator. In my case i always know which separator i used. For example if i use snake case i know the separator will be "_" and i call ToCamelCase(str,"_");. Also i think if you have unknown number of combination your string, it will be hard to know what seperator set.

    public string ToCamelCase(string str,string sep)
    {
       str = str.Split(new[] {sep}, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => char.ToUpperInvariant(s[0]) + s.Substring(1, s.Length - 1))
            .Aggregate(string.Empty, (s1, s2) => s1 + s2);
        return str.First().ToString().ToLowerInvariant() + str.Substring(1);
    }
Community
  • 1
  • 1
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28