Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JavaScriptSerializer exclude properties with null/default values?

I'm using JavaScriptSerializer to serialize some entity objects.

The problem is, many of the public properties contain null or default values. Is there any way to make JavaScriptSerializer exclude properties with null or default values?

I would like the resulting JSON to be less verbose.

like image 869
frankadelic Avatar asked Sep 07 '09 06:09

frankadelic


2 Answers

FYI, if you'd like to go with the easier solution, here's what I used to accomplish this using a JavaScriptConverter implementation with the JavaScriptSerializer:

private class NullPropertiesConverter: JavaScriptConverter {  public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {   throw new NotImplementedException();  }   public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) {   var jsonExample = new Dictionary<string, object >();   foreach(var prop in obj.GetType().GetProperties()) {    //check if decorated with ScriptIgnore attribute    bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);     var value = prop.GetValue(obj, BindingFlags.Public, null, null, null);    if (value != null && !ignoreProp)     jsonExample.Add(prop.Name, value);   }    return jsonExample;  }   public override IEnumerable<Type> SupportedTypes {   get {    return GetType().Assembly.GetTypes();   }  } } 

and then to use it:

var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] {   new NullPropertiesConverter() }); return serializer.Serialize(someObjectToSerialize); 
like image 121
Mitch Avatar answered Oct 02 '22 07:10

Mitch


The solution that worked for me:

The serialized class and properties would be decorated as follows:

[DataContract] public class MyDataClass {   [DataMember(Name = "LabelInJson", IsRequired = false)]   public string MyProperty { get; set; } } 

IsRequired was the key item.

The actual serialization could be done using DataContractJsonSerializer:

public static string Serialize<T>(T obj) {   string returnVal = "";   try   {     DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());     using (MemoryStream ms = new MemoryStream())     {       serializer.WriteObject(ms, obj);       returnVal = Encoding.Default.GetString(ms.ToArray());     }   }   catch (Exception /*exception*/)   {     returnVal = "";     //log error   }   return returnVal; } 
like image 42
frankadelic Avatar answered Oct 02 '22 06:10

frankadelic