How to serialize boolean to JSON as strings using Jackson

15,919

Solution 1

Okay, it seems that either my IDE or Maven was acting up and refused to build or reference the changes I made in my ObjectMapper configuration.

For the sake of the future visitors, here is the gist of the solution to the issue of making Jackson data binding to spit out boolean values as strings:

In my customized ObjectMapper context resolver, I just had to add special serializer for boolean object types:

// create a module with a custom Boolean serializer
SimpleModule module = new SimpleModule("BooleanAsString", new Version(1, 0, 0, null, null, null));
module.addSerializer(new NonTypedScalarSerializerBase<Boolean>(Boolean.class){
    @Override
    public void serialize(Boolean value, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonGenerationException {
        ObjectMapperProvider.log.debug("serializing boolean value as a Strng");
        jgen.writeString(value.toString());
    }
});
// Here's where we configure the object mapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

That's it. If you know how to configure your ObjectMapper, then this should be enough to get you going.

Solution 2

Jackson 2.16 Custom Serializer for primitive data type . you should write your own serializer. example code for boolean data type

// create a module with a custom Boolean serializer

class BooleanSerializer extends JsonSerializer<Boolean> {
private final static Logger logger =    LoggerFactory.getLogger(BooleanSerializer.class);
@Override
public void serialize(Boolean value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    logger.info("serializing boolean value as a Strng {}",value);
    jgen.writeString(value.toString());
}

}

//register custom BooleanSerializer class with ObjectMapper.

// Here's where we configure the object mapper

 ObjectMapper mapper = new ObjectMapper();

 SimpleModule simpleModule = new SimpleModule("BooleanAsString", new    Version(1, 0, 0, null, null, null));
    simpleModule.addSerializer(Boolean.class,new BooleanSerializer());
    simpleModule.addSerializer(boolean.class,new BooleanSerializer());

mapper.registerModule(module);
Share:
15,919
Roland Tepp
Author by

Roland Tepp

I'm a developer, (surprise - eh!) For the last 5 years or so I've been professionally involved in writing Java in and with Eclipse (using big E both - as an IDE and as a platform) From the past, I still harbour some softness for Python language and web (client side) technologies like HTML, CSS and Javascript. Occasionally dusting off my knowledge of these and keeping them from completely rusting away... In my more distant youth I've also dabbled in wide range of languages and technologies, starting from BASIC, followed up bu Pascal, bits and pieces of C/C++ (enough to shoot myself in a foot), just a tad bit of assembler (just enough to know that is not the kind of programming I would love to do for any extended period of time), various of dialects of SQL, perl and bunch of stuff that don't even measuer up to being mentioned...

Updated on July 25, 2022

Comments

  • Roland Tepp
    Roland Tepp almost 2 years

    We have developed a REST service using Jersey JAX-RS and Jackson (version 2.1.5) for JSON serialization.

    As the application is supposed to be a drop-in replacement for the older legacy service acting as a backend to an existing mobile app, we need to do some tweaking to the way Jackson serializes boolean values.

    Existing mobile app expects boolean values to be expressed as strings of "true" and "false" like this:

    {"Foo":"true","Bar":"false"}
    

    So I have searched for a way to influence the Jackson serialization to output booleans as strings, but I have no success.

    Oh, and btw - since our model classes have been generated from xml schemas using JAXB class generation, we can not annotate the classes with json annotations.

    I have tried to register a module with ObjectMapper, that provides a customized serializer for boolean objects, but it did not seem to work.

  • Roland Tepp
    Roland Tepp over 8 years
    This is basically exactly same as the accepted answer: stackoverflow.com/a/19682113/1712
  • Roland Tepp
    Roland Tepp over 8 years
    From what I can tell some minor details might be slightly different but the gist of it all is same.
  • Srinivas Bheemreddy
    Srinivas Bheemreddy over 8 years
    thanks.i taken your answer as a reference.i just extends JsonSerializer.i think it's the correct way to create custom serializer in jackson 2.6
  • Alfredo M
    Alfredo M over 6 years
    The type NonTypedScalarSerializerBase<Boolean> is deprecated