20

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.

Sachin
  • 40,216
  • 7
  • 90
  • 102
user2199888
  • 211
  • 1
  • 2
  • 4

8 Answers8

23

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

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
13

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; }
Sachin
  • 40,216
  • 7
  • 90
  • 102
9

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});
Daniel Mohr
  • 654
  • 7
  • 7
3
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

Community
  • 1
  • 1
tam tam
  • 1,870
  • 2
  • 21
  • 46
  • Great answer with no need to use 3rd party libraries AND with no need of changing the serialized classes. – Chris W Oct 01 '15 at 08:08
2

You can use JsonConvert from Newtonsoft.json rather than JavaScriptSerializer

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

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

1

Old question, but today with .net6 you can do:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<string> midname;

And you midname list will not appear in the serialized object.

glihm
  • 1,138
  • 13
  • 29
0

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"}