Mastero Mastero -4 years ago 296
C# Question

Convert JSON String from Camel case to Pascal case using C#

I'm having a JSON string, it has Key in the form of Camel-case but I need to convert the Key to Pascal-case.

Actual JSON String

string jsonString = "{\"personName\":{\"firstName\":\"Emma\",\"lastName\":\"Watson\"}}";


Expected JSON String : Needs to convert from the above JSON string.

string jsonString = "{\"PersonName\":{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}}";


Kindly assist me how to convert this using C#.

Answer Source

Because I can't sleep.

If you define the following static class of extension methods...

public static class JsonExtensions
{
    public static void Capitalize(this JArray jArr)
    {
        foreach(var x in jArr.Cast<JToken>().ToList())
        {
            var childObj = x as JObject;
            if(childObj != null)
            {
                childObj.Capitalize();
                continue;
            }
            var childArr = x as JArray;
            if(childArr != null)
            {
                childArr.Capitalize();
                continue;
            }
        }
    }

    public static void Capitalize(this JObject jObj)
    {
        foreach(var kvp in jObj.Cast<KeyValuePair<string,JToken>>().ToList())
        {
            jObj.Remove(kvp.Key);
            var newKey = kvp.Key.Capitalize();
            var childObj = kvp.Value as JObject;
            if(childObj != null)
            {
                childObj.Capitalize();
                jObj.Add(newKey, childObj);
                return;
            }
            var childArr = kvp.Value as JArray;
            if(childArr != null)
            {
                childArr.Capitalize();
                jObj.Add(newKey, childArr);
                return;
            }
            jObj.Add(newKey, kvp.Value);
        }
    }

    public static string Capitalize(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            throw new ArgumentException("empty string");
        }
        char[] arr = str.ToCharArray();
        arr[0] = char.ToUpper(arr[0]);
        return new string(arr);
    }
}

You can:

void Main()
{
    string jsonString = 
        "{\"personName\":{\"firstName\":\"Emma\",\"lastName\":\"Watson\"}}";
    var jObj = JObject.Parse(jsonString);
    jObj.Capitalize();
    Console.WriteLine(jObj.ToString()); //yay!
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download