How does Json. Net modify attribute values before serialization?
We all know the use of Json.net sequence words Test = new test () {A = "123", B = DateTime. now, C = DateTime. now. addDays (1)}; string json = JsonConvert. serializeObject (test); you will find that the code of this string will generate the following: 1 {"A": "123", "B": "2014-09-14T19: 08: 11.8653266 + 08: 00 "," C ":" 2014-09-15T19: 08: 11.8663266 + 08: 00 "} There is no problem in itself. If you encounter a relatively simple requirement: I want the Json string generated by B and C not to display the time. I want it to display the time difference in seconds (int type) how can I deal with this problem? I have asked many people not to do this. I have also obtained some suggestions, such as modifying the generated string or adding it to the object class. The two attributes show that this can solve the problem, but if I have 10 classes and one hundred classes, and each class has a different attribute name than each class... I thought it was terrible. Later I gave up this idea. I was wondering if there was any way to modify the value of this attribute before generating the Json string.... Later, I checked the Json.net source code and found A method code: copy the code class Test {public string A {get; set;} public DateTime B {get; set;} public DateTime? C {get; set ;}} class Program {static void Main (string [] args) {Test test = new Test () {A = "123", B = DateTime. now, C = DateTime. now. addDays (1)}; JsonConverter jc = new DateConverter (); string json = JsonConvert. serializeObject (test, jc); Console. writeLine (json) ;}} public class DateConverter: JsonConverter {public override void WriteJson (JsonWriter writer, object value, JsonSerializer s Erializer) {DateTime I = (DateTime) value; writer. writeValue ("Previously I could modify the DateTime Type value in the Model");} public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {throw new NotImplementedException ();} public override bool CanConvert (Type objectType) {if (objectType = typeof (DateTime) return objectType = typeof (DateTime ); else if (objectType = Typeof (DateTime ?)) Return objectType = typeof (DateTime ?); Else return false ;}}