If you are using Newtonsoft.Json to serialize the object to json you can use the DefaultValueHandling setting to tell it to ignore properties that do not have a value set.
public class TestSerialize
{
public int Height { get; set; }
public int Width { get; set; }
}
class Program
{
static void Main(string[] args)
{
var serializeMe = new TestSerialize() {Height = 12};
Newtonsoft.Json.JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(serializeMe, settings);
Console.WriteLine(json);
}
}
If you are using System.Text.Json you can use the JsonSerializerOption DefaultIgnoreCondition. Set it to WhenWritingDefault
System.Text.Json.JsonSerializerOptions options = new JsonSerializerOptions()
{DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault};
string json2 = System.Text.Json.JsonSerializer.Serialize(serializeMe, options);
Console.Write(json2);
Added Javascript serializer example. Add a class to help with serialization. it will exclude nulls or "0"
public class DefaultPropertiesConverter : 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 && value.ToString() != "0" && !ignoreProp)
jsonExample.Add(prop.Name, value);
}
return jsonExample;
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return GetType().Assembly.GetTypes();
}
}
}
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] {
new DefaultPropertiesConverter()
});
string json3 = serializer.Serialize(serializeMe);