1

Using Spring Boot, I'm exposing a REST API that accepts my domain object as a JSON body and attempts to persist it to a Mongo Document. How can I accept lowercase values of this enum in the JSON request and save them to Mongo as lowercase as well?

Sammy
  • 3,395
  • 7
  • 49
  • 95

1 Answers1

1

Regarding accepting lowercase values of the enum, you can refer this answer

Regarding saving them to MongoDB in lowercase as well, you need to write custom converters and register the same.

A typical write converter can be something like:

@WritingConverter
public final class YourEnumWriteConverter implements Converter<YourEnum, String> {
    @Override
    public String convert(YourEnum source) {
        return source == null ? "" : source.name().toLowerCase();
    }
}

You also need to write the corresponding read converter to read the lowercase string as enum successfully from DB. A typical read converter will look like:

@ReadingConverter
public final class YourEnumReadConverter implements Converter<String, YourEnum> {
    @Override
    public YourEnum convert(String source) {
        return source == null ? null : Arrays.stream(YourEnum.values()).
                                              filter(enumInstance -> enumInstance.name().equalsIgnoreCase(source.trim())).
                                              findFirst().
                                              orElse(null);
    }
}

where Converter belongs to the package org.springframework.core.convert.converter and the two class annotations belong to the package org.springframework.data.convert.

And then in your @Configuration file, just register the same as:

@Bean
public CustomConversions customConversions() {
    List<Converter<?, ?>> converterList = new ArrayList<>();
    converterList.add(new YourEnumWriteConverter());
    converterList.add(new YourEnumReadConverter());
    return new CustomConversions(converterList);
}

where CustomConversions belong to org.springframework.data.mongodb.core.convert

This should solve your problem. One important thing to note here is, if you want all the enums in your application or maybe a particular set of enums present in your application to be persisted as lowercase, I would suggest to write ConverterFactory instead of individually writing a pair of Converters for each such enum. This answer is already long, so not writing about setting up ConverterFactory

Some links that will be helpful:

Mongo Custom Converters

Spring Type Conversion

Another useful SO question

Clouren
  • 372
  • 1
  • 3
  • 10
Vikas Prasad
  • 3,163
  • 5
  • 28
  • 39