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

試著忘記壹切 提交于 2019-12-12 19:06:32

问题


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


回答1:


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!
}


来源:https://stackoverflow.com/questions/44511199/convert-json-string-from-camel-case-to-pascal-case-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!