Dhaval Patel
Dhaval Patel

Reputation: 7601

How to filter null or empty value from Json string

I have a one Model it's look like

public class DataClass
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string ContactNo { get; set; }
}

and I tried to convert in Json request using below mentioned code.

var l=new List<Data>();
l.Add(new Data(){Name="foo",Address ="bar",ContactNo =123});
l.Add(new Data(){Name="biz",Address ="baz"});
string json=JsonConvert.SerializeObject(l);

it will give me string like

 [{"Name":"foo","Address":"bar","ContactNo":"123"},{"Name":"biz","Address":"baz","ContactNo":""}]

in output second ContactNo has a empty string but I don't need the field which has a no value or NULL . can anyone please tell me what is the best way to avoid NULL or Empty field from Json request? Thanks in Advance.

Upvotes: 1

Views: 5255

Answers (3)

PMBjornerud
PMBjornerud

Reputation: 880

I assume you are using Json.Net.

You can use the System.ComponentModel.DefaultValueAttribute. This allows you to mark a property to use a different default value than null.

So, if you want empty strings to be ignored in your JSON output you can update the model class to look like this:

public class DataClass
{
    [DefaultValue("")]
    public string Name { get; set; }
    [DefaultValue("")]
    public string Address { get; set; }
    [DefaultValue("")]
    public string ContactNo { get; set; }
}

Note that the SerializerSettings.DefaultValueHandling must be set to Ignore or IgnoreAndPopulate for this to be picked up.

A more thorough example of various approaches for reducing serialized json size is here:

http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

Upvotes: 1

user2492798
user2492798

Reputation: 589

1.You may add a flag in the model class.

public class DataClass{
public bool isIllegal{get;set;}
public string Name { get; set; }
public string Address { get; set; }
public string ContactNo { get; set{isIllegal=!string.isNullOrEmpty(value);)}
}

2.You can filter data whose isIllegal is false after JsonConvert.SerializeObject(l).

Upvotes: 0

santosh singh
santosh singh

Reputation: 28652

Change your model as below

public class Data
{
    public string Name { get; set; }
    public string Address { get; set; }
    public int? ContactNo { get; set; }
}

and then serialize your object as below

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

Upvotes: 1

Related Questions