21

I know about ScriptIgnoreAttribute.

But what if I want to ignore a property based on criteria. For example how to ignore a nullable property on serialization only if it's null and doesn't contain any value?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
iLemming
  • 34,477
  • 60
  • 195
  • 309

3 Answers3

41

https://learn.microsoft.com/dotnet/api/system.web.script.serialization.scriptignoreattribute

Use [ScriptIgnore]

using System;
using System.Web.Script.Serialization;

public class Group
{
    // The JavaScriptSerializer ignores this field.
    [ScriptIgnore]
    public string Comment;

    // The JavaScriptSerializer serializes this field.
    public string GroupName;
}
mtone
  • 1,685
  • 15
  • 29
akdora
  • 893
  • 1
  • 9
  • 19
  • 2
    I haven't upvoted this because although it helped me out it doesn't answer the asked question. – Liath Nov 23 '17 at 10:10
  • Does it work on properties that were implemented for an Interface? since I still get an error in JSON de-serialize? Since it didn't work in my case – OZ_CM Aug 11 '21 at 10:12
8

Best possible answer I have is to make your own JavaScriptConverter and parse the property based on your own condition(s).

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
  //...
  if (!object.ReferenceEquals(dictionary["MyProperty"],null)){
    // My Code
  }
  //...
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • I decided to use a method that will return a dictionary which contains only those objects that need to be serialized. And then serialize that dictionary. – iLemming May 16 '11 at 14:27
  • 1
    @Agzam: Overkill? Debatable. If you wanted full control over the serialization of the objects, this is the route to go. The JavaScriptSerializer class returns a native dictionary anyways, this just gives you the freedom of placing it in your own custom object. When I'm dealing with abstract information, i'll usually use the dynamic keyword and parse the data myself. – Brad Christie May 16 '11 at 14:29
3

I used internal instead of public properties and it worked for me

relly
  • 439
  • 3
  • 3