csharp 序列化词典时保留外壳

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 序列化词典时保留外壳相关的知识,希望对你有一定的参考价值。

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

以上是关于csharp 序列化词典时保留外壳的主要内容,如果未能解决你的问题,请参考以下文章

csharp 数组,列表,词典,Pocos

csharp 数组,列表,词典,Pocos

csharp 用于以所选元素阵列的词典顺序生成所有排列的扩展方法。

csharp 型号序列化时忽略

Python基础 序列和词典

.NET 6 - 更改 Json 属性外壳