Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refine json by remove null values properties and zero (0) value properties from the c# object

Scenario:

I have to send a Httpwebrequest and server demands it will accept only two values as Json format, I want to send one more request to another server and that demands one value at a time in Json format.

For above scenario I created a Class and provide all three properties like following

pubilc class MyClass
{
    public string as { get; set;}
    public int value { get; set;}
    public string asd { get;s et;}
}

For the first HttpWebRequest, to the first server, I want to send only two properties from MyClass 'as' and 'asd' now I will serialize through JsonConvert function of NewtonSoft as following

MyClass class = new MyClass();
string json = JsonConvert.SerializeObject(class);

The above syntax will return json having 0 and null values properties, NewtonSoft provide the functions to remove the null value from Json but it can't remove the properties having value 0, or you can say if your property data type is int and there is no any value assigned than it assign 0 to those properties.

Syntax to remove Null properties from Json

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

The above syntax will remove the null values during serialize the MyClass object.

Now Question how to remove properties from json if it has properties having 0.

like image 471
Ashish-BeJovial Avatar asked Dec 08 '22 05:12

Ashish-BeJovial


2 Answers

You can try to define your int property as nullable:

public int? value { get; set;}
like image 50
mgigirey Avatar answered Dec 10 '22 19:12

mgigirey


Just modify your expression

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

as below,

string json = JsonConvert.SerializeObject(
  class, 
  Newtonsoft.Json.Formatting.Indented, 
  new JsonSerializerSettings { 
    NullValueHandling = NullValueHandling.Ignore,
    DefaultValueHandling = DefaultValueHandling.Ignore 
  }
);
like image 34
Ashu_Rjt Avatar answered Dec 10 '22 18:12

Ashu_Rjt