How to exclude some members from serialization in Json?

I have an object that I want to serialize in Json format I use:

public string ToJson() { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); string sJSON = jsonSerializer.Serialize(this); return sJSON; } 

How to define some fields in "this" so as not to serialize?

+7
source share
3 answers

A possible way is to declare these fields as private or internal .

An alternative solution is to use the DataContractJsonSerializer class. In this case, you add the DataContract attribute to your class. You can manage the members that you want to serialize with the DataMember - all the elements marked with it are serialized, and the rest are not.

You should rewrite your ToJson method as follows:

  public string ToJson() { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(<your class name>)); MemoryStream ms = new MemoryStream(); jsonSerializer.WriteObject(ms, this); string json = Encoding.Default.GetString(ms.ToArray()); ms.Dispose(); return json; } 
+4
source
+22
source

Check out the JavaScriptConverter class. You can register converters to customize the serialization / deserialization process for certain types of objects. Then you can enable the properties you want without making any changes to the source class.

+2
source

All Articles