Skip to content

Instantly share code, notes, and snippets.

@jhlee8804
Last active June 3, 2023 01:15
Show Gist options
  • Save jhlee8804/fd1759ff8c456ce4f14c6c2b281cc60b to your computer and use it in GitHub Desktop.
Save jhlee8804/fd1759ff8c456ce4f14c6c2b281cc60b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Keep casing when serializing dictionaries
/// cf. https://stackoverflow.com/a/24226442/3781540
/// </summary>
public class CamelCaseExceptDictionaryKeysResolver
//: CamelCasePropertyNamesContractResolver
: JsonNullToEmptyContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
#if DEBUG
if (properties != null)
{
// base 클래스의 프로퍼티가 먼저 출력되도록 보정
return properties.OrderBy(p => BaseTypesAndSelf(p.DeclaringType).Count()).ToList();
}
#endif
return properties;
}
/// <summary>
/// cf. https://stackoverflow.com/a/32572740/3781540
/// </summary>
public static IEnumerable<Type> BaseTypesAndSelf(Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment