How to convert any pascal json object to camel json object?

I tried using CamelCasePropertyNamesContractResolver, however it does not convert pascal property names to camel shell?

Note: this is just an example, my json input is unknown, I only json pascal body.

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


    }
}
+4
source share
2 answers

Your example serializes a string. If you convert your input to an object and then deserialize, it will work:

    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();
    }
+6
source

Humanizer has features like Pascalize and Camelize. You can use it or just look at your code.

    /// <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);
    }

The results are as follows:

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

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

Source: https://habr.com/ru/post/1673089/


All Articles