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.
You can try to define your int property as nullable:
public int? value { get; set;}
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
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With