CSharp · Console
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
namespace ConsoleApp6
{
public class Program
{
public static void Main(string[] args)
{
// Enum
Dictionary<MyEnum, int> dictionary = new Dictionary<MyEnum, int>();
dictionary.Add(MyEnum.Foo, 1);
var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCaseExceptDictionaryKeysResolver();
string json = JsonConvert.SerializeObject(dictionary, settings);
Console.WriteLine(json);
Console.WriteLine();
// DateTime
Dictionary<DateTime, int> dictionary2 = new Dictionary<DateTime, int>();
dictionary2.Add(DateTime.Now, 1);
json = JsonConvert.SerializeObject(dictionary2, settings);
Console.WriteLine(json);
Console.WriteLine();
// Class
Dictionary<MyClass, int> dictionary3 = new Dictionary<MyClass, int>();
dictionary3.Add(new MyClass(), 1);
json = JsonConvert.SerializeObject(dictionary3, settings);
Console.WriteLine(json);
Console.WriteLine();
}
public class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = myDelegate;
return contract;
}
private Func<string, string> myDelegate = (x) => {
Console.WriteLine("I am the DictionaryKeyPolicy and I am resolving key " + x);
return x;
};
}
private enum MyEnum
{
Foo,
Bar
}
[TypeConverter(typeof(MyClassTypeConverter))]
private class MyClass { }
private class MyClassTypeConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return "MyClassKeyAfterTypeConverter";
}
}
}
}