BoolConvert.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Reflection;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. namespace PublicLibrary.Json
  6. {
  7. public class BoolConvert : JsonConverter
  8. {
  9. private string v;
  10. private string[] vs;
  11. //private string fields;
  12. //是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化
  13. public override bool CanRead => false;
  14. //是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化
  15. public override bool CanWrite => true;
  16. public BoolConvert(string v)
  17. {
  18. this.v = v;
  19. this.vs = v.Split(",");
  20. //this.fields = fields;
  21. }
  22. public override bool CanConvert(Type objectType)
  23. {
  24. return typeof(string) == objectType;
  25. }
  26. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  27. {
  28. throw new NotImplementedException();
  29. }
  30. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  31. {
  32. ////new一个JObject对象,JObject可以像操作对象来操作json
  33. //var jobj = new JObject();
  34. //value参数实际上是你要序列化的Model对象,所以此处直接强转
  35. var model = value as string;
  36. //string tempName = "";
  37. //// 获得此模型的公共属性
  38. //PropertyInfo[] propertys = model.GetType().GetProperties();
  39. //foreach (PropertyInfo pi in propertys)
  40. //{
  41. // tempName = pi.Name; // 检查fields是否包含此列
  42. // if (fields.Contains(tempName))
  43. // {
  44. // if (pi.GetValue(model).ToString() != "Y")
  45. // {
  46. // //如果ID值为1,添加一个键位"ID",值为false
  47. // jobj.Add(tempName, vs[1]);
  48. // }
  49. // else
  50. // {
  51. // jobj.Add(tempName, vs[0]);
  52. // }
  53. // }
  54. // else
  55. // {
  56. // jobj.Add(tempName, pi.GetValue(model).ToString());
  57. // }
  58. //}
  59. string targetvalue = string.Empty;
  60. if (model != "Y")
  61. {
  62. targetvalue = vs[1];
  63. }
  64. else
  65. {
  66. targetvalue = vs[0];
  67. }
  68. //通过ToString()方法把JObject对象转换成json
  69. var jsonstr = targetvalue;
  70. //调用该方法,把json放进去,最终序列化Model对象的json就是jsonstr,由此,我们就能自定义的序列化对象了
  71. writer.WriteValue(jsonstr);
  72. }
  73. }
  74. }