Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude some members from being serialized to Json?

I have an object that I want to serialize to Json format I'm using:

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

How do I define some fields in "this" to not be serialized?

like image 827
Elad Benda Avatar asked Jun 21 '11 09:06

Elad Benda


3 Answers

Use the ScriptIgnoreAttribute.

like image 152
Roman Bataev Avatar answered Sep 19 '22 06:09

Roman Bataev


The possible way is to declare those fields as private or internal.

The alternative solution is to use DataContractJsonSerializer class. In this case you add DataContract attribute to your class. You can control the members you want to serialize with DataMember attribute - all members marked with it are serialized, and the others 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;
    }
like image 38
Eugene Avatar answered Sep 18 '22 06:09

Eugene


Check out the JavaScriptConverter class. You can register converters to customize the serialization/deserialization process for specific object types. You can then include the properties that you want, without making any changes to the original class.

like image 21
MikeWyatt Avatar answered Sep 21 '22 06:09

MikeWyatt