- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a JSON object to an enum using Jackson in Java?
A JSONObject can parse the text from String to produce a Map kind of an object. An Enum can be used to define a collection of constants, when we need a predefined list of values which do not represent some kind of numeric or textual data then we can use an enum. We can convert a JSON object to an enum using the readValue() method of ObjectMapper class.
In the below example, we can convert/deserialize a JSON object to Java enum using the Jackson library.
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
Advertisements