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扩展方法中加上JsonConverter参数来接收需要屏蔽的类型
/// <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
联系我:renhanlinbsl@163.com