/// <summary> /// html编码序列化转换器 /// </summary> public class HtmlEncodeConverter : JsonConverter { //是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化 public override bool CanRead => false; //是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化 public override bool CanWrite => true; public override bool CanConvert(Type objectType) { return typeof(string) == objectType || objectType.IsClass; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else { Type type = value.GetType(); if (type == typeof(string)) { writer.WriteValue(HttpUtility.HtmlEncode(value)); } else if (type.IsClass) { JObject jo = new JObject(); foreach (PropertyInfo prop in type.GetProperties()) { if (prop.CanRead) { object propVal = prop.GetValue(value, null); if (propVal != null) { if (propVal.GetType() == typeof(string)) { jo.Add(prop.Name, JToken.FromObject(System.Web.HttpUtility.HtmlEncode(propVal), serializer)); } else { jo.Add(prop.Name, JToken.FromObject(propVal, serializer)); } } } } jo.WriteTo(writer); } else { writer.WriteValue(value); } } } }View Code
标签:Newtonsoft,propVal,writer,value,Json,HtmlEncodeConverter,override,序列化,public From: https://www.cnblogs.com/5tomorrow/p/16745623.html