This is a very incomplete post with some quick & dirty notes about serializing objects in ASP.Net WebForms. All included code is VB.Net.

Default ASP.Net serialization

  • Classes must have annotation <Serializable> to be serialized by the default serializer
  • Use annotation <NonSerialized> on properties to be left out of serialization
  • Navigation Properties (Entity Framework) can’t be marked as <NonSerialized>, so you may end up with circular references when the serialization attempts to follow all relationships (e.g. child has reference to a parent, and parent has reference to all children)
  • Any private variable/property will by default be left out of the serialization

Newtonsoft Json.Net Serialization

  • No need for <Serializable> annotation; any object/class can be serialized
  • Use annotation <JsonIgnore> on any properties to be left out of the serialization
  • Navigation Properties (Entity Framework) can have annotation <JsonIgnore> to be left out of the serialization, preventing circular references and unnecessary data from being included
  • I haven’t tested if private variables are included in the serialization, but it seems likely

Serialization and ViewState

Anything stored in ViewState is serialized. When you reference ViewState("SomeKey") directly (or through a property), any objects not already serialized will be automatically serialized using built-in serialization. Also, when you access ViewState("SomeKey"), you are getting a reference to the value in the ViewState, and any changes made will affect the actual values behind the reference. For example:

CType(ViewState("SomeKey"), List(Of String)).Add("test")

After running this code, ViewState("SomeKey") will contain the new entry. This is because ViewState(“SomeKey”) is giving you the reference to the actual value, not a copy of the value.

On the other hand, if you were to use Json.Net serializer to serialize an object before adding it to ViewState, when you deserialize it you will be getting a copy of the value (not a reference to it), and direct updates won’t affect the value in ViewState. For example:

JsonConvert.DeserializeObject(ViewState("SomeKey"), GetType(List(Of String))).Add("New Entry")

After running this code, ViewState("SomeKey") will not contain the new entry, as the function DeserializeObject returns a deserialized copy of the value in ViewState, not a reference to the value in ViewState.

To use Json.Net and ViewState, you will have to retrieve the value from ViewState, deserialize it to a local variable, make your changes, reserialize it, then save it back to ViewSate.

Dim TestList as List(Of String)
TestList = JsonConvert.DeserializeObject(ViewState("SomeKey"), GetType(List(Of String)))
lstTest.Add("New Entry")
ViewState("SomeKey") = JsonConvert.SerializeObject(TestList)