8

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?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

3 Answers3

23

Use the ScriptIgnoreAttribute.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Roman Bataev
  • 9,287
  • 2
  • 21
  • 15
  • 3
    +1. This is the correct answer. I'm glad I read through the answers to the bottom, or I would've missed this. Works beautifully. – gilly3 Jul 22 '12 at 07:42
  • 1
    @karaxuna, it is supported down to 3.5 (which is when the JavascriptSerializer was introduced) – xr280xr May 13 '14 at 16:53
4

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;
    }
Eugene
  • 2,858
  • 1
  • 26
  • 25
2

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.

MikeWyatt
  • 7,842
  • 10
  • 50
  • 71
  • Nice, but i be still difficult if I want a string member to be serialized while another string member to be not. right? – Elad Benda Jun 21 '11 at 12:52
  • You basically return a dictionary of key/value pairs, so it would be up to your custom converter to simply include one and not the other. You could even serialize each member (or not) based on its value. – MikeWyatt Jun 21 '11 at 13:41