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

001 picture 001 · Mar 24, 2017 · Viewed 13.6k times · Source

I tried using CamelCasePropertyNamesContractResolver, however it does not convert pascal property names into camel casing?

Note: this is an example only, my json input is unknown, I only the json pascal casing.

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


    }
}

Answer

swatsonpicken picture swatsonpicken · Mar 24, 2017

Your example is serialising a string. If you convert your input to an object then deserialise, 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();
    }