Reputation: 189
I have the following code :
public City[] Cities { get; set; }
In City class, I have two properties
public string Name { get; set; }
public string Code { get; set; }
When a request comes that has this Cities
field empty I would like to hide this with Newtonsoft.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public City[] Cities { get; set; }
But this code I have tried does not work because Cities
is not null, but empty and the request always has the two properties in this array.
How should I use Newtonsoft in this case? Is there any additional check for the objects here needed?
Upvotes: 2
Views: 6492
Reputation: 6073
You should use Conditional Property Serialization in JSON.NET. I think you are going to ignore this property if it's empty or null so, inside the class contains Cities
properties add this method:
// ignore a property on a condtion
public bool ShouldSerializeCities() => Cities != null && Cities.Count > 0;
Update 1:
As @DavidG mentioned the workaround above won't ignore string fields (Name and Code) if they are null or empty. For making that happen you need to make use of DefaultValue
:
Define JsonConvert
settings like this:
var settings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
Use DefaultValue
attribute over your desiarred field/properties:
public class City
{
[DefaultValue("")]
public string Name
{
get;
set;
}
[DefaultValue("")]
public string Code
{
get;
set;
}
}
Serialize your object with the settings you created above:
JsonConvert.SerializeObject(obj, settings) ;
For example, if your object looks like this:
var obj = new Foo{
Cities = new [] {
new City() {Name = "A", Code = ""}
, new City() {Name = "B", Code = "C"}
, new City(){Name = "", Code = ""}
}
};
The result will be:
{
"Cities": [
{
"Name": "A"
},
{
"Name": "B",
"Code": "C"
},
{}
]
}
I created a project on .NET Fiddle to see how it works.
If you don't like creating new settings, you still can use ShuldSerializeMemberName
inside your City
class:
public class City
{
public string Name{get;set;}
public bool ShouldSerializeName() => !string.IsNullOrEmpty(Name);
}
Upvotes: 7