Conditional ScriptIgnore for JSON Serialization

Is there a way to conditionally exclude elements from JSON serialization? I am using C # in a .NET4 application with WebAPI. I have [DataMember]it [ScriptIgnore]already in my classes, and everything works fine. What I want to do does not include specific properties at runtime based on the value of the property

For example, I can only serialize List<Foo> myFoowhen

myFoo != null && myFoo.Count > 0

JSON is translated back to my own JS objects on the client, which will have all the properties created already as myFoo: []. There is simply no need to send them in JSON to the client, since it will essentially not affect the object and will only send more data and use more processing on the client. This is a very JS heavy HTML5 mobile site and I try to reduce as much data and processing as possible.

+3
source share
3 answers

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

0
source

OP , - , . , , , . , Json.net , :

public class Tricorn
{
   public string RocketFuel { get; set; }

   public bool ShouldSerializeRocketFuel()
   {
      return !string.IsNullOrEmpty(this.RocketFuel.Length);
   }
}

"ShouldSerialze" . , , Json.net - . , !

+7

Using a getter might be the best choice 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;
      }
   }
}
0
source

All Articles