Reputation: 368
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.
Upvotes: 3
Views: 4736
Reputation: 7857
Thanks OP for answering your question, but some more info would have been great as I ran into the same situation. It was grueling, but I finally found the way to do it. There isn't much out there about it, but according to a lowly page on Json.net's archive here's how it works:
public class Tricorn
{
public string RocketFuel { get; set; }
public bool ShouldSerializeRocketFuel()
{
return !string.IsNullOrEmpty(this.RocketFuel.Length);
}
}
The key is making a method with a predicate "ShouldSerialze" to your property name. The returning value indicates whether it should be serialized and Json.net handles the rest. Hope this helps anyone!
Upvotes: 7
Reputation: 368
I found Json.net which will allow me to do conditional serialization at runtime.
Upvotes: 0
Reputation: 7857
Using a getter might be your best bet here:
[ScriptIgnore]
private List<Foo> myFoo;
public List<Foo> MyFoo
{
get
{
if (this.myFoo != null && this.myFoo.Count > 0)
{
return this.myFoo;
}
else
{
return null;
}
}
}
Upvotes: 0