search
HomeJavajavaTutorialSerializing an enum in a Spring Boot web application

Serializing an enum in a Spring Boot web application

Enum is a good structure to define a set of limited and well defined values inside the domain of our application. They could help to prevent impossible states in our codebase.

The scenario

Let's use a note taking web application as an example to show the possible ways to serialize and deserialize an eum value.

We are going to implement it using Spring Boot 3.3.x and MongoDB.

We define a Type enum class to represent the permitted types of todos inside the application: events and activities.

public enum Type {
    EVENT("event"),
    ACTIVITY("activity");

    private Type(String value) {
       this.value = value;
    }

   public String getValue() {
       return value;
    }

}

Our Todo class

public class Todo {

    private String id;
    private String name;
    private boolean completed;

    private Type type;

    ...
    ...

}

We are going to analyze enum serialization in these scenarios:

  1. Enum as query param.
  2. Enum as part of a JSON body request.
  3. Enum as a field of a MongoDB document.

Enum as query param

In this scenario we need only a deserialize method because we are interested in transforming from a string value to the enum.

Below a snippet of code representing the Controller method to read all todos by types, the type is passed as a query parameter.

 public Collection<todo> read(@RequestParam(required = false) Type type) {
     ...
     ...
 }
</todo>

The query parameter is a string so we have to define an appropriate Converter to transform it.
Inside the convert method we call Type.fromString, a static method created in the enum class, that will be used in other scenarios too. The code of fromString method is presented in the next scenario.

public class StringToType implements Converter<string type> {

    @Override
    public Type convert(String source) {
        return Type.fromString(source);
    }

}
</string>

The converter must be registered in the application.

@Configuration
public class Config implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToType());
        WebMvcConfigurer.super.addFormatters(registry);
    }
}

Now when we will use Type as a RequestParam the StringToType converter will be used to try converting string values in our enum.

Enum as part of JSON body request

To manage correctly the enum as a field of the JSON body content we should add some code to the enum Type class.

We need to use the annotation @JsonValue to mark the field as the value to use for serializing the enum.
Then we should add a static map inside the enum to map the Type with the related string representation.

public enum Type {
    EVENT("event"),
    ACTIVITY("activity");

    @JsonValue
    private String value;

    private static Map<string type> enumMap;

    private Type(String value) {
        this.value = value;
    }

    static {
        enumMap = Stream.of(values()).collect(Collectors.toMap(t -> t.value, t -> t));
    }

    public static Type fromString(String value) {
        return enumMap.get(value);
    }

    public String getValue() {
        return value;
    }

}
</string>

Enum as a field of a MongoDB document.

To manage the serialization/deserialization of a enum in a MongoDB document we have to use the @ValueConverter annotation that binds a field of the document with a specific PropertyValueConverter class.

In the example the field Type type is bound with the MongoEnumConverter that provide read and write methods to manage the conversion.

@Document(collection = "todo")
@TypeAlias("todo")
public class Todo {

    @Id
    private String id;
    private String name;
    private boolean completed;

    @ValueConverter(MongoEnumConverter.class)
    private Type type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

}

In detail in the read method we call Type.fromString from the enum class to try to convert the string in a valid Type instance.

public enum Type {
    EVENT("event"),
    ACTIVITY("activity");

    private Type(String value) {
       this.value = value;
    }

   public String getValue() {
       return value;
    }

}

In conclusion

In this article I presented some ways to manage the serialization/deserializion of a enum class in a typical Web scenario. Spring and the Jackson library provide some facilities to simplify this work.

The code is publically available in this Gitlab repository.

The code presented in this article are under CC0 license.

The above is the detailed content of Serializing an enum in a Spring Boot web application. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

How does the underlying hardware architecture affect Java's performance?How does the underlying hardware architecture affect Java's performance?Apr 28, 2025 am 12:05 AM

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Explain why native libraries can break Java's platform independence.Explain why native libraries can break Java's platform independence.Apr 28, 2025 am 12:02 AM

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!