using System; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PublicLibrary.Json { public class BoolConvert : JsonConverter { private string v; private string[] vs; //private string fields; //是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化 public override bool CanRead => false; //是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化 public override bool CanWrite => true; public BoolConvert(string v) { this.v = v; this.vs = v.Split(","); //this.fields = fields; } public override bool CanConvert(Type objectType) { return typeof(string) == objectType; } 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) { ////new一个JObject对象,JObject可以像操作对象来操作json //var jobj = new JObject(); //value参数实际上是你要序列化的Model对象,所以此处直接强转 var model = value as string; //string tempName = ""; //// 获得此模型的公共属性 //PropertyInfo[] propertys = model.GetType().GetProperties(); //foreach (PropertyInfo pi in propertys) //{ // tempName = pi.Name; // 检查fields是否包含此列 // if (fields.Contains(tempName)) // { // if (pi.GetValue(model).ToString() != "Y") // { // //如果ID值为1,添加一个键位"ID",值为false // jobj.Add(tempName, vs[1]); // } // else // { // jobj.Add(tempName, vs[0]); // } // } // else // { // jobj.Add(tempName, pi.GetValue(model).ToString()); // } //} string targetvalue = string.Empty; if (model != "Y") { targetvalue = vs[1]; } else { targetvalue = vs[0]; } //通过ToString()方法把JObject对象转换成json var jsonstr = targetvalue; //调用该方法,把json放进去,最终序列化Model对象的json就是jsonstr,由此,我们就能自定义的序列化对象了 writer.WriteValue(jsonstr); } } }