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 Overflow
Discussions

C# Ignore empty Prop in Json
Hi I want to the empty property in my Json to not show up Current output … More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
How to suppress writing empty string value to JSON (C#, .NET 8, System.Text.Json) - Stack Overflow
I think it would help if the strings were null instead of empty. ... You can't use a JsonConverter to ignore a property. But you could, if you wanted, add a custom modifier that checks for converters that implement some interface with a ShouldSerialize(object parent, object? More on stackoverflow.com
🌐 stackoverflow.com
c# - How to ignore empty strings in API JSON response? - Stack Overflow
You can customize the JSON contract used by the DefaultJsonTypeInfoResolver or derived type. Below code changes each property of type string to only serialize when not null and not empty. More on stackoverflow.com
🌐 stackoverflow.com
c# - Remove empty string properties from json serialized object - Stack Overflow
Just decorating the properties [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] ONLY should do what you want. Unless the property is getting set to an empty string. More on stackoverflow.com
🌐 stackoverflow.com
🌐
ServiceStack
forums.servicestack.net › servicestack.text › json
Extend ExcludeDefaultValues to ignore empty strings - JSON - ServiceStack Customer Forums
November 13, 2018 - I can use the ExcludeDefaultValues to exclude json serializing of null values in strings. But I also want "" to be excluded. I do not have access to the model to set custom attributes. Is there a way to create a kind of override in the string serializer? In Newtonsoft I can do: protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); if (property.PropertyType == ty...
🌐
Medium
madhawapolkotuwa.medium.com › ignoring-null-values-in-json-serialization-in-c-de6783cc3d3b
Ignoring null Values in JSON Serialization in C# | by Madhawa Polkotuwa | Medium
August 30, 2024 - var orderWithAddress = new OrderResponse { Id = Guid.NewGuid(), Status = OrderStatus.Shipped, DeliveryAddress = new AddressResponse { Street = "123 Main St", City = "Springfield", ZipCode = "12345" } }; var orderWithoutAddress = new OrderResponse { Id = Guid.NewGuid(), Status = OrderStatus.Pending, DeliveryAddress = null // This will be ignored in the JSON output }; ... var options = new JsonSerializerOptions { WriteIndented = true }; string jsonWithAddress = JsonSerializer.Serialize(orderWithAddress, options); string jsonWithoutAddress = JsonSerializer.Serialize(orderWithoutAddress, options); Console.WriteLine("Order with Address:"); Console.WriteLine(jsonWithAddress); Console.WriteLine("\nOrder without Address:"); Console.WriteLine(jsonWithoutAddress);
Find elsewhere
Top answer
1 of 2
7

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();
2 of 2
0

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 }
            },
        };
    }
}
🌐
Java Guides
javaguides.net › 2019 › 04 › jackson-ignore-null-and-empty-fields-on-serialization.html
Jackson Ignore Null and Empty Fields on Serialization
April 24, 2019 - We can configure Include.NON_NULL and Include.NON_EMPTY at property level as well as at class level using @JsonInclude annotation. package net.javaguides.jackson.annotations; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class Employee { private int id; @JsonInclude(Include.NON_NULL) private String firstName; @JsonInclude(Include.NON_EMPTY) private String lastName; public Employee(int id, String firstName, String lastName) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; } public int getId(
🌐
LogicBig
logicbig.com › tutorials › misc › jackson › json-include-non-empty.html
Jackson JSON - @JsonInclude NON_EMPTY Example
public class ExampleMain { public static void main(String[] args) throws IOException { Employee employee = new Employee(); employee.setName("Trish"); employee.setDept(""); employee.setAddress(null); employee.setPhones(new ArrayList<>()); employee.setSalary(new AtomicReference<>()); ObjectMapper om = new ObjectMapper(); String jsonString = om.writeValueAsString(employee); System.out.println(jsonString); } }
🌐
Postman
community.postman.com › help hub
Skip Property in JSON File If It Contains an Empty String - Help Hub - Postman Community
January 14, 2022 - I have a JSON File that looks something like this. I want to be able to skip the discounts property if it is empty. [ { "state": "CT", "postalCode": "06010", "species": "Cat", "unit": "years", "value": …
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-ignore-the-null-and-empty-fields-using-the-jackson-library-in-java
How to ignore the null and empty fields using the Jackson library in Java?
May 12, 2025 - Use the @JsonInclude annotation at the class level, and set the value to Include.NON_NULL and Include.NON_EMPTY. Create a constructor and getter methods for the fields. Create an ObjectMapper object, and enable pretty printing using the enable(SerializationFeature.INDENT_OUTPUT) method. Use the writeValueAsString() method of the ObjectMapper class to convert the object to a JSON string.
🌐
Conrad Akunga
conradakunga.com › blog › handling-null-and-empty-strings-with-system-text-json
Handling Null And Empty Strings With System.Text.Json | Conrad Akunga - Building Software In .NET
March 9, 2021 - public class NullToEmptyStringConverter : JsonConverter<string> { // Override default null handling public override bool HandleNull => true; // Check the type public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(string); } // Ignore for this example public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } // public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { if (value == null) writer.WriteStringValue(""); else writer.WriteStringValue(value); } }
🌐
ConcretePage
concretepage.com › jackson-api › jackson-ignore-null-and-empty-fields
Jackson Ignore Null and Empty Fields
ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); mapper.setSerializationInclusion(Include.NON_EMPTY); In the above code we have configured ObjectMapper with Include.NON_NULL and Include.NON_EMPTY using setSerializationInclusion() that ignore Null and Empty values globally for every class. Now when we write JSON using mapper instance for any given object, then the properties of that object having null or empty value will not be included in JSON. For example if we want to write any object into JSON as string we will write code as following.
🌐
Baeldung
baeldung.com › home › json › jackson › remove null objects in json response when using spring and jackson
Remove Null Objects in JSON Response When Using Spring and Jackson | Baeldung
June 20, 2024 - @JsonInclude(Include.NON_EMPTY) ... phoneNumbers = new ArrayList<>(); // constructors, getters and setters } We can use Include.NON_EMPTY to exclude the values if they’re empty....
🌐
Baeldung
baeldung.com › home › json › jackson › ignore null fields with jackson
Ignore Null Fields with Jackson | Baeldung
February 9, 2026 - How to control which fields get serialized/deserialized by Jackson and which fields get ignored. ... Jackson supports configuring null exclusion directly on a class. This approach scopes the behavior to a single type and keeps global configuration untouched: @JsonInclude(Include.NON_NULL) public class MyDto { ... } For finer control, the same annotation can be applied to individual fields instead: public class MyDto { @JsonInclude(Include.NON_NULL) private String stringValue; private int intValue; // standard getters and setters }
🌐
javakeypoint
javakeypoint.wordpress.com › 2019 › 11 › 10 › jackson-ignore-empty-and-null-fields
How to Ignore Empty and Null Fields using Jackson . | javakeypoint
November 10, 2019 - In the above code we have configured ObjectMapper with Include.NON_NULL and Include.NON_EMPTY using setSerializationInclusion() that ignore Null and Empty values globally for every class. Now when we write JSON using mapper instance for any given object, then the properties of that object having null or empty value will not be included in JSON. Find the example of Include.NON_NULL and Include.NON_EMPTY with ObjectMapper Book.java · package com.web.model; public class Student{ private int student_id; private String student_name; private String student_phone; private String student_address; public student_address(){} public Student(int student_id, String student_name, String student_phone, String student_address) { this.student_id= student_id; this.student_name= student_name; this.student_phone= student_phone; this.student_address= student_address; } //setter and getter }
🌐
HowToDoInJava
howtodoinjava.com › home › jackson › jackson – ignoring null, empty and absent values
Jackson - Ignoring Null, Empty and Absent Values - HowToDoInJava
September 1, 2022 - ObjectMapper mapper = new ObjectMapper(); ... mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); Now this mapper will ignore all the NULL fields for all the classes it serializes. We can further customize the check for emptiness by creating a custom filter class and overriding its equals() method. If equals() returns true value is excluded (that is, filtered out); if false value is included. ... class StringFilter { @Override public boolean equals(Object value) { //custom logic return true; } }