See the docs on Custom Serializers; there's an example of exactly this, works for me.

In case the docs move let me paste the relevant answer:

Converting null values to something else

(like empty Strings)

If you want to output some other JSON value instead of null (mainly because some other processing tools prefer other constant values -- often empty String), things are bit trickier as nominal type may be anything; and while you could register serializer for Object.class, it would not be used unless there wasn't more specific serializer to use.

But there is specific concept of "null serializer" that you can use as follows:

// Configuration of ObjectMapper:
{
    // First: need a custom serializer provider
   StdSerializerProvider sp = new StdSerializerProvider();
   sp.setNullValueSerializer(new NullSerializer());
   // And then configure mapper to use it
   ObjectMapper m = new ObjectMapper();
   m.setSerializerProvider(sp);
}

// serialization as done using regular ObjectMapper.writeValue()

// and NullSerializer can be something as simple as:
public class NullSerializer extends JsonSerializer<Object>
{
   public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider)
       throws IOException, JsonProcessingException
   {
       // any JSON value you want...
       jgen.writeString("");
   }
}
Answer from enigment on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 20654810 › jackson-deserializing-null-strings-as-empty-strings
java - Jackson: deserializing null Strings as empty Strings - Stack Overflow
I have the following class, that is mapped by Jackson (simplified version): public class POI { @JsonProperty("name") private String name; } In some cases the server returns "name": null an...
Discussions

java - Change JSON value from null to empty String - Stack Overflow
im making a rest controller which return json. i get this data from database, mapping in to java class using setter getter. { "example": null, "this": null, "is"... More on stackoverflow.com
🌐 stackoverflow.com
September 22, 2020
json - gson: Treat null as empty String - Stack Overflow
I use google-gson to serialize a Java map into a JSON string. It provides a builder handles null values: More on stackoverflow.com
🌐 stackoverflow.com
How to deserialize a blank JSON string value to null for java.lang.String? - Stack Overflow
I am trying a simple JSON to de-serialize in to java object. I am however, getting empty String values for java.lang.String property values. In rest of the properties, blank values are converting to null values(which is what I want). More on stackoverflow.com
🌐 stackoverflow.com
java - Spring boot, Jackson Convert empty string into NULL in Serialization - Stack Overflow
I have a requirement that while doing serialization I should be able to to convert all the properties that are with Empty string i.e "" to NULL, I am using Jackson in Spring boot, any idea how can I More on stackoverflow.com
🌐 stackoverflow.com
December 27, 2019
🌐
Google Groups
groups.google.com › g › dropwizard-user › c › 9RACX-_SrUU
Serialize null return values to empty string and not 'null'
If you want to strip out the nulls entirely (e.g. ["4", "6"]) then filter your array before you return it: List<Object> builder = new ArrayList<Object>(arr.length); for (Object o : arr) { builder.add(o); } return builder.toArray(); To be honest, working with an Object[] screams at me that you're probably doing something a bit odd. Are the elements not all Strings? TL;DR: Resolve the nulls on the server-side, before you serialize the result as a JSON object.
🌐
Google Groups
groups.google.com › g › google-gson › c › W3eXzqCnZ6U
Replace null with empty string on serialization
December 2, 2010 - On Dec 2, 1:36 pm, abp <adr...@needful.de> wrote: > is it possible to write an empty string instead of null to the json, > when it encounters nulls in my pojos? My bet would be to define a custom converter for the String class. Something like this: public class StringConverter implements JsonSerializer<String>, JsonDeserializer<String> { public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) { if ( src == null ) { return new JsonPrimitive(""); } else { return new JsonPrimitive(src.toString()); } public String deserialize(JsonElement json, Type typeOfT, JsonD
Find elsewhere
🌐
Java By Examples
javabyexamples.com › control-how-jackson-serializes-null-values
Control How Jackson Serializes Null Values
Here, the name field which is null is in the resulting JSON string. Now let's switch to properties - fields with accessors. ... public class GetterPerson { private String name; private int age; public GetterPerson() { } public GetterPerson(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } Here, GetterPerson has two fields and public accessor methods. When we serialize an instance of GetterPerson, it also serializes null properties - null returning getter methods:
🌐
CodingTechRoom
codingtechroom.com › question › deserialize-empty-json-string-null-java
How to Deserialize an Empty JSON String to null for java.lang.String in Java? - CodingTechRoom
null : value; } } class MyObject ... MyObject.class); // obj.myString will be null. The Java JSON library used (e.g., Jackson or Gson) treats empty strings as valid, resulting in an empty string instead of null....
🌐
GitHub
github.com › FasterXML › jackson-module-kotlin › issues › 440
Kotlin FeatureRequest: Serialize null string to empty string · Issue #440 · FasterXML/jackson-module-kotlin
May 5, 2021 - @Singleton class JacksonRegisterCustomObjectMapperCustomizer : ObjectMapperCustomizer { override fun customize(mapper: ObjectMapper) { val sp = DefaultSerializerProvider.Impl() sp.setNullValueSerializer(NullSerializer.instance) val stringModule = SimpleModule() stringModule.addSerializer(String::class.javaObjectType, StringSerializer()) stringModule.addSerializer(String::class.javaPrimitiveType, StringSerializer()) stringModule.addSerializer(String::class.java, StringSerializer()) mapper.registerModule(stringModule).setSerializerProvider(sp) } class StringSerializer : JsonSerializer<String?>() { override fun serialize(string: String?, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) { when { string.isNullOrBlank() -> jsonGenerator.writeString("") else -> jsonGenerator.writeString(string) } } } }
Author: FasterXML
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – working with maps and nulls
Jackson – Working With Maps and Nulls
May 2, 2023 - class MyDtoNullKeySerializer extends StdSerializer<Object> { public MyDtoNullKeySerializer() { this(null); } public MyDtoNullKeySerializer(Class<Object> t) { super(t); } @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName(""); } } Now the Map with the null key will work just fine – and the null key will be written as an empty String: @Test public void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException { ObjectMapper mapper = ne
🌐
GitHub
github.com › schmittjoh › serializer › issues › 566
Serialize null values as empty string · Issue #566 · schmittjoh/serializer
March 31, 2016 - Hi, I would like to force the serialization of null values as empty strings '' instead of null. I set the option setSerializeNull(true) to force serialization of null values, but how to tra...
Author: schmittjoh
🌐
Baeldung
baeldung.com › home › json › jackson › include null value in json serialization
Include null Value in JSON Serialization | Baeldung
June 21, 2025 - The toString() method also provides a string representation of the object in a JSON-like format for easy debugging. Please note that including @JsonProperty annotations ensures that all relevant fields are accurately serialized into the JSON ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-serialize-a-null-field-using-gson-library-in-java
How to serialize a null field using Gson library in Java?
import com.google.gson.*; import com.google.gson.annotations.*; public class NullFieldSerializationExample { public static void main(String args[]) { Gson gson = new GsonBuilder() .serializeNulls() .setPrettyPrinting() .create(); Employee emp = new Employee(null, 25, 40000.00); String jsonEmp = gson.toJson(emp); System.out.println(jsonEmp); } } // Employee class class Employee { @Since(1.0) public String name; @Since(1.0) public int age; @Since(2.0) public double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } }
🌐
Reddit
reddit.com › r/csharp › serialize object to empty object {} instead of null with system.text.json
r/csharp on Reddit: Serialize object to empty object {} instead of null with System.Text.Json
March 15, 2024 -

Using:

  • .net 8

  • System.Text.Json serializer.

Let's say I have a two classes defined like this:

public class SampleClass
{
    public SampleClassDetail? FirstProperty { get; set; }
    public SampleClassDetail? SecondProperty { get; set; }
}
public class SampleClassDetail
{
    public int MyProperty { get; set; }
}

And an instance of `SampleClass` :

SampleClass sample = new()
{
    FirstProperty = new SampleClassDetail { MyProperty = 1 }
};

Then I want to serialize it with `System.Text.Json`:

string serialized = JsonSerializer.Serialize(sample);

This produces:

{
  "FirstProperty": {
    "MyProperty": 1
  },
  "SecondProperty": null
}

But I would the null to be treated like: `"SecondProperty": {}`

I've tried creating a CustomJson Converter and adding it to the options:

public class SampleClassDetailConverter : JsonConverter<SampleClassDetail?>
{
    public override SampleClassDetail? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, SampleClassDetail? value, JsonSerializerOptions options)
    {
        if (value == null)
        {
            writer.WriteStartObject();
            writer.WriteEndObject();
        }
        else
        {
            var newOptions = new JsonSerializerOptions(options);
            newOptions.Converters.Remove(this);
            JsonSerializer.Serialize(writer, value, newOptions);
        }
    }
}
var options = new JsonSerializerOptions();
options.Converters.Add(new SampleClassDetailConverter());
string serialized = JsonSerializer.Serialize(sample, options);

But still getting the same.

I've created a dotnetfiddle:

https://dotnetfiddle.net/PsXrxt

Any idea how to achieve this?

Top answer
1 of 5
32
What you're asking for doesn't make sense. If they need to be objects in the output JSON, then the properties shouldn't be nullable, and should be initialized by default. something like public class MyClass { public Sample PropertyOne { get; set; } = new(); public Sample PropertyTwo { get; set; } = new(); }
2 of 5
18
You are on the right track but by default, JsonConverter ignores null values. You have to override the HandNull property. Find the section title "Handle null values" from these docs https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-8-0 Converter Class: public class SampleClassDetailConverter : JsonConverter { public override bool HandleNull => true; public override SampleClassDetail Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, SampleClassDetail value, JsonSerializerOptions options) { if (value == null) { writer.WriteStartObject(); writer.WriteEndObject(); } else { JsonSerializer.Serialize(writer, value, value.GetType(), options); } } } Also, I'm not sure if adding the converter to the options like that will work (It could I just can't remember) but I know that annotating the class object will: public class SampleClass { [JsonConverter((typeof(SampleClassDetailConverter)))] public SampleClassDetail? FirstProperty { get; set; } [JsonConverter((typeof(SampleClassDetailConverter)))] public SampleClassDetail? SecondProperty { get; set; } }