4

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#.

4

1 Answer 1

6

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!
}
Sign up to request clarification or add additional context in comments.

2 Comments

Tried to edit the code in order to fix a small bug - the return in the collection iteration would prevent other items to be iterated and capitalize, so that should be a continue instead.
@eyal When I get a moment, I'll review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.