如何将任何 pascal case JSON 对象转换为 camel case JSON 对象?

How to convert any pascal case JSON object to camel case JSON object?

我尝试使用 CamelCasePropertyNamesContractResolver,但它无法将 Pascal 属性 名称转换为驼峰式大小写?

注意:这只是一个示例,我的 json 输入未知,我只有 json pascal 大小写。

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {

            object myJsonInput = @"{'Id':'123','Name':'abc'}"; //Example only, any json.

            object myJsonOutput;

            var jsonSerializersettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            myJsonOutput = JsonConvert.DeserializeObject<object>(myJsonInput.ToString(),jsonSerializersettings);
            //{{"Id": "123","Name": "abc"}}
        }


    }
}

Humanizer有Pascalize、Camelize等函数。你可以使用它或者只看他们的源代码。

    /// <summary>
    /// By default, pascalize converts strings to UpperCamelCase also removing underscores
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string Pascalize(this string input)
    {
        return Regex.Replace(input, "(?:^|_)(.)", match => match.Groups[1].Value.ToUpper());
    }

    /// <summary>
    /// Same as Pascalize except that the first character is lower case
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string Camelize(this string input)
    {
        var word = Pascalize(input);
        return word.Substring(0, 1).ToLower() + word.Substring(1);
    }

结果如下:

"some_title".Pascalize() => "SomeTitle"

"some_title".Camelize() => "someTitle"

你的例子是序列化一个字符串。如果将输入转换为对象然后反序列化,它将起作用:

    static void Main(string[] args)
    {
        var myJsonInput = @"{'Id':'123','Name':'abc'}";
        var jsonSerializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        var interimObject = JsonConvert.DeserializeObject<ExpandoObject>(myJsonInput);
        var myJsonOutput = JsonConvert.SerializeObject(interimObject, jsonSerializerSettings);

        Console.Write(myJsonOutput);
        Console.ReadKey();
    }