question

JulioBello-4525 avatar image
0 Votes"
JulioBello-4525 asked vb2ae commented

Remove Properties with Value Equal to Zero in JSON String

Hi, Everybody!...

I have a JSON string I need to alter before it gets sent as part of a request. I wish to remove any instances where the following string is encountered:

"<property>":0

where <property> is a placeholder for a property (e.g., "height":0, "width":0, "length":0, etc.). In other words, <property> is not a literal.

However, I do not wish any of the following to be removed (e.g., "height":0.1, "width":0.2, "length":0.3, etc.) thus resulting in .1, .2, .3, etc., respectively.

Also, I do not wish to leave "orphaned commas" (e.g., "height":0.1, ,"length":0.3) where width was zero.

Is there a RegEx for this?









dotnet-csharpdotnet-runtimedotnet-standard
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

vb2ae avatar image
0 Votes"
vb2ae answered vb2ae commented

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);


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, vb2ae...

Thank-you for your prompt response.

I am actually using System.Web.Script.Serialization in conjunction with the DataContract and the DataMember to generate the JSON.

Do you know if System.Web.Script.Serialization has similar options?

Please advise.

Truly grateful.



0 Votes 0 ·

added an example for javascript serializer

0 Votes 0 ·