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

我尝试使用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"}}
        }


    }
}
最佳答案
您的示例是序列化字符串.如果您将输入转换为对象然后反序列化,它将起作用:

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

转载注明原文:c# – 如何将任何pascal case JSON对象转换为camel case JSON对象? - 代码日志