c# - How to prevent an entire class from being serialized? -


i using newtonsoft.json serialize class , of members. there 1 particular class many of members instance of, i'd tell class not serialized @ all, if member instance of type skipped.

is possible in c# appending sort of attribute class mark non-serializable?

i not think can done using attribute on class. should able implementing custom jsonconverter serializes , deserializes instance of class null. code implements such behavior:

class ignoringconverter : jsonconverter {     public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         writer.writenull();     }      public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         return null;     }      public override bool canconvert(type objecttype)     {         return objecttype == typeof(classtoignore);     } } 

in example, classtoignore class wish ignore during serialization. such classes should decorated jsonconverter attribute:

[jsonconverter(typeof(ignoringconverter))] class classtoignore 

you can register converter default converter useful if you're using asp.net web api.

i have included console application sample demonstrate functionality:

using system; using newtonsoft.json;  /// <summary> /// class want serialize. /// </summary> class classtoserialize {     public string mystring { get; set; } = "hello, serializer!";      public int myint { get; set; } = 9;      /// <summary>     /// null after serializing or deserializing.     /// </summary>     public classtoignore ignoredmember { get; set; } = new classtoignore(); }  /// <summary> /// ignore instances of class. /// </summary> [jsonconverter(typeof(ignoringconverter))] class classtoignore {     public string nonserializedstring { get; set; } = "this should not serialized."; }  class ignoringconverter : jsonconverter {     public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         writer.writenull();     }      public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         return null;     }      public override bool canconvert(type objecttype)     {         return objecttype == typeof(classtoignore);     } }  class program {     static void main(string[] args)     {         var obj = new classtoserialize();         var json = jsonconvert.serializeobject(obj);          console.writeline(json);          obj = jsonconvert.deserializeobject<classtoserialize>(json);          // note obj.ignoredmember == null @ point          console.readkey();     } } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -