You have the annotation in the wrong place - it needs to be on the class, not the field. i.e:
@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case
public static class Request {
// ...
}
As noted in comments, in versions below 2.x the syntax for this annotation is:
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY
The other option is to configure the ObjectMapper directly, simply by calling
mapper.setSerializationInclusion(Include.NON_NULL);
(for the record, I think the popularity of this answer is an indication that this annotation should be applicable on a field-by-field basis, @fasterxml)
Answer from drew moore on Stack OverflowYou have the annotation in the wrong place - it needs to be on the class, not the field. i.e:
@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case
public static class Request {
// ...
}
As noted in comments, in versions below 2.x the syntax for this annotation is:
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY
The other option is to configure the ObjectMapper directly, simply by calling
mapper.setSerializationInclusion(Include.NON_NULL);
(for the record, I think the popularity of this answer is an indication that this annotation should be applicable on a field-by-field basis, @fasterxml)
You can also set the global option:
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
C# Ignore empty Prop in Json
How to suppress writing empty string value to JSON (C#, .NET 8, System.Text.Json) - Stack Overflow
c# - How to ignore empty strings in API JSON response? - Stack Overflow
c# - Remove empty string properties from json serialized object - Stack Overflow
One thing you can do is customize the serialization options by modifying the type info resolver, and setting ShouldSerialize to true for string properties with Length > 0:
var serializerOptions = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
info =>
{
foreach (var jsonPropertyInfo in info.Properties)
{
if (jsonPropertyInfo.PropertyType == typeof(string))
{
jsonPropertyInfo.ShouldSerialize =
(_, str) => str is string { Length: > 0 };
}
}
}
}
}
};
var serialized = JsonSerializer.Serialize(new MyClass(), serializerOptions);
Console.WriteLine(serialized); // prints "{"IntProp":0}"
See Customize a JSON contract and Example: Conditional Serialization for more info.
I didn't like any of the answers. I just went with a second property:
[JsonIgnore]
public string StringProp
{
get => _stringProp ?? string.Empty;
set => _stringProp = String.IsNullOrWhiteSpace( value )
? null
: value.Trim();
}
/// <summary>
/// Don't want StringProp in all the JSONs if it is irrelevant. So need
/// to do this hack.
/// </summary>
[JsonInclude]
[JsonPropertyName( "StringProp" )]
[JsonIgnore( Condition = JsonIgnoreCondition.WhenWritingNull )]
private string? _stringProp ;
Just decorating the properties [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] ONLY should do what you want. Unless the property is getting set to an empty string.
Just wondering, why do you need the DataMemeber attribute?
Here is a link to a working dotnetfiddle
using System;
using Newtonsoft.Json;
using System.ComponentModel;
public class Program
{
public static void Main()
{
var user = new User();
user.UserID = "1234";
user.ssn = "";
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
Console.WriteLine(JsonConvert.SerializeObject(user, settings));
}
}
public class User
{
[DefaultValue("")]
public string UserID { get; set; }
[DefaultValue("")]
public string ssn { get; set; }
[DefaultValue("")]
public string empID { get; set; }
[DefaultValue("")]
public string schemaAgencyName { get; set; }
[DefaultValue("")]
public string givenName { get; set; }
[DefaultValue("")]
public string familyName { get; set; }
[DefaultValue("")]
public string password { get; set; }
}
You can also use two annotations as follows:
[DefaultValue("")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Category { get; set; }
I have resolved this problem. I have removed the null values during serialization.
string JSONstring = JsonConvert.SerializeObject(dt, new
JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
});
And after that empty string values are removed through the following code
var temp = JArray.Parse(JSONstring);
temp.Descendants()
.OfType<JProperty>()
.Where(attr => attr.Value.ToString() == "")
.ToList() // you should call ToList because you're about to changing the result, which is not possible if it is IEnumerable
.ForEach(attr => attr.Remove()); // removing unwanted attributes
JSONstring = temp.ToString();
This may Help
namespace JSON
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Root
{
[DefaultValue("")]
[JsonProperty("allOrNone")]
public bool AllOrNone { get; set; }
[DefaultValue("")]
[JsonProperty("records")]
public Record[] Records { get; set; }
}
public partial class Record
{
[DefaultValue("")]
[JsonProperty("Address__c")]
public string AddressC { get; set; }
[DefaultValue("")]
[JsonProperty("ConsentToComm__c")]
public string ConsentToCommC { get; set; }
[DefaultValue("")]
[JsonProperty("EmailCLDate__c")]
public string EmailClDateC { get; set; }
[DefaultValue("")]
[JsonProperty("attributes")]
public Attributes Attributes { get; set; }
}
public partial class Attributes
{
[DefaultValue("")]
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class Root
{
public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Root self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = ShouldSerializeContractResolver.Instance,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
To ignore empty string use default value handling option and set property default value to empty string
[DefaultValue("")]
public string key { get; set; }
And in set JsonSerializerSettings as below
new JsonSerializerSettings
{ DefaultValueHandling = DefaultValueHandling.Ignore }
public class Sample
{
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public string Test { get; set; }
}