How to remove null value in json string

.net, asp.net, c#, json

Solution

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`

Problem

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.

Original source

Related problems