Home > Java > javaTutorial > 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
Release: 2023-09-05 12:13:06
forward
1471 people have browsed it

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,
   }
}
Copy after login

Output

CONTRACT
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template