'How to remove null value in json string

Hi I'm using the below class

Public List<string> name;
Public List<string> midname;

Once I serialize it I'm getting the following output like

 {"name":[hari],"midname":null}

But I want my answer to be like this

{"name":[hari]}

It shouldn't display the class attribute that has null value and I'm using c# .net framework.



Solution 1:[1]

The full answer depends on how you're serializing your class.

If you're using data contracts to serialize your classes, set EmitDefaultValue = false

[DataContract]
class MyClass
{
    [DataMember(EmitDefaultValue = false)]
    public List<string> name;

    [DataMember(EmitDefaultValue = false)]
    public List<string> midname { get; set; }
}

If you're using Json.Net, try this instead

class MyClass
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<string> name;

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<string> midname { get; set; }
}

Or set it globally with JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

Solution 2:[2]

If you are using Json.Net then You can try this by Decorating your property like this

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<string> name { get; set; }

Solution 3:[3]

Like p.s.w.g said, best to serialize properly in the first place. An example of serializing without nulls can be seen here

e.g.

var json = JsonConvert.SerializeObject(
        objectToSerialize,
        new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});

Solution 4:[4]

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

The following is how you will utilize the above and it will ignore null values.

var serializer = new JavaScriptSerializer();
    serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() });
    return serializer.Serialize(someObjectToSerialize);

Source

Solution 5:[5]

You can use JsonConvert from Newtonsoft.json rather than JavaScriptSerializer

var result = JsonConvert.SerializeObject(obj, 
            new JsonSerializerSettings() 
            { 
                NullValueHandling = NullValueHandling.Ignore 
            });

Solution 6:[6]

string signatureJson = JsonConvert.SerializeObject(signature, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

Solution 7:[7]

In case of using System.Text.Json (which is a recommendation for performance reasons). This is another workaround to get rid of null values, in my case is not feasible to use a decorator because of the amount of properties, so let's use a JsonSerializerOptions instead:

var content = new ContentToParse() { prop1 = "val", prop2 = null };

string json = System.Text.Json.JsonSerializer.Serialize(content, new 
     System.Text.Json.JsonSerializerOptions()  { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull 
    });
//json {"prop1":"val"}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 p.s.w.g
Solution 2 Sachin
Solution 3 Daniel Mohr
Solution 4 Community
Solution 5 Sri Raghava
Solution 6 mehman abasov
Solution 7 Felipe Sierra