zoukankan      html  css  js  c++  java
  • jsonconvert 序列化时忽略指定的类型

     /// <summary>
        /// 自定义转换类
        /// </summary>
        public class CustomConverter<T> : JsonConverter<T>
        {
            public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
            {
                return existingValue;
            }
    
            public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
            {
                //遇到指定的类型时返回null,也可以使用JsonWriter writer内部字段根据名称进行扩展...
                writer.WriteNull();
            }
        }
    

    转json扩展

    /// <summary>
            /// 将对象序列化成Json字符串
            /// </summary>
            /// <param name="obj">需要序列化的对象</param>
            /// <param name="jsonConverterArray"></param>
            /// <param name="ignoreNullValue">是否忽略值未null的字段</param>
            /// <returns></returns>
            public static string ToJson(this object obj, JsonConverter[] jsonConverterArray, bool ignoreNullValue = false)
            {
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    NullValueHandling = ignoreNullValue ? NullValueHandling.Ignore : NullValueHandling.Include,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    MaxDepth = 2,
                    Converters = jsonConverterArray
                };
                return JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
            }
    

    使用

     var commandConverter = new CustomConverter<ICommand>();
                var frameworkElementConverter = new CustomConverter<FrameworkElement>();
    
                JsonConverter[] jsonConverters = { commandConverter, frameworkElementConverter };
                oldSelectPageJson = obj.ToJson(jsonConverters);
    
    留待后查,同时方便他人
    联系我:renhanlinbsl@163.com
  • 相关阅读:
    Linux中的用户和用户组
    GCC编译过程
    C++设计模式——单例模式(转)
    快速排序之python
    归并排序之python
    计数排序之python
    希尔排序之python
    插入排序之python
    选择排序之python
    冒泡排序之python
  • 原文地址:https://www.cnblogs.com/ives/p/15272865.html
Copyright © 2011-2022 走看看