Remove Properties with Value Equal to Zero in JSON String

Julio Bello 221 Reputation points
2021-03-26T07:12:56.097+00:00

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?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,367 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,119 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2021-03-26T08:37:35.943+00:00

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