问题
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"}}
}
}
}
回答1:
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();
}
回答2:
Humanizer has functions such as Pascalize and Camelize. You can use it or just look at their sorce 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);
}
Results being the following:
"some_title".Pascalize() => "SomeTitle"
"some_title".Camelize() => "someTitle"
来源:https://stackoverflow.com/questions/42994125/how-to-convert-any-pascal-case-json-object-to-camel-case-json-object