Search code examples
c#jsonjsonserializer

Conditional ScriptIgnore for JSON Serialization


Is there a way to conditionally exclude items from JSON serialization? I'm using C# in a .NET4 application with WebAPI. I have [DataMember] and [ScriptIgnore] already on my classes and everything works fine. What I want to do is not include certain properties at runtime based on the property's value

For instance, I may only want to serialize List<Foo> myFoo when

myFoo != null && myFoo.Count > 0

The JSON is translated back into my own JS objects on the client, which will have all properties instantiated already like myFoo: []. It's just unnecessary to send these in JSON to the client as it essentially will have no effect on the object and only is sending more data and using more processing on the client. It's a very JS heavy HTML5 mobile site and I'm trying to reduce as much data and processing as I can.


Solution

  • I found Json.net which will allow me to do conditional serialization at runtime.