Home  >  Article  >  Java  >  How to convert JSON object to enum type in Java using Jackson?

How to convert JSON object to enum type in Java using Jackson?

PHPz
PHPzforward
2023-09-05 12:13:061410browse

How to convert JSON object to enum type in Java using Jackson?

JSONObject can parse the text in a string to generate an object of type Map. Enumerations can be used to define constant collections . We can use enumerations when we need a predefined list of values ​​that does not represent some kind of numeric or text data. We can convert a JSON object into an enumeration using the readValue() method of the ObjectMapper class.

In the example below, we can use the Jackson library to convert/deserialize a JSON object into a Java enumeration.

Example

import com.fasterxml.jackson.databind.*;
public class JSONToEnumTest {
   public static void main(String arg[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      Employee emp = mapper.readValue("{\"jobType\":\"CONTRACT\"}", Employee.class);
      System.out.println(emp.getJobType());
   }
   public static class Employee {
      private JobType jobType;
      public JobType getJobType() {
         return jobType;
      }
      public void setJobType(JobType jobType) {
         this.jobType = jobType;
      }
   }
   public enum JobType {
      PERMANENT,
      CONTRACT,
   }
}

Output

CONTRACT

The above is the detailed content of How to convert JSON object to enum type in Java using Jackson?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete