DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Introduction to Polymorphism With Database Engines in NoSQL Using Jakarta NoSQL
  • JSON Handling With GSON in Java With OOP Essence
  • Proper Java Exception Handling
  • Postgres JSON Functions With Hibernate 6

Trending

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Grafana Loki Fundamentals and Architecture
  1. DZone
  2. Coding
  3. Languages
  4. Converting JSON to POJOs Using Java

Converting JSON to POJOs Using Java

If you find yourself mapping JSON to POJOs but don't want to write a full class, help yourself to a handy library that does the work for you.

By 
Anurag Jain user avatar
Anurag Jain
·
May. 30, 17 · Tutorial
Likes (55)
Comment
Save
Tweet
Share
266.6K Views

Join the DZone community and get the full member experience.

Join For Free

If you have JSON that you want to map into a POJO without writing the full POJO class, then you can make use of the jsonschema2pojo library. This is an excellent library that can create Java classes using your input JSON.

Prerequisites

Program Language: Java

Pom Dependency:

<dependency>  
    <groupId>org.jsonschema2pojo</groupId>  
    <artifactId>jsonschema2pojo-core</artifactId>  
    <version>0.4.35</version>  
</dependency>


Git Repo: https://github.com/csanuragjain/extra/tree/master/convertJson2Pojo

Program

Main method:

      public static void main(String[] args) {  
           String packageName="com.cooltrickshome";  
           File inputJson= new File("."+File.separator+"input.json");  
           File outputPojoDirectory=new File("."+File.separator+"convertedPojo");  
           outputPojoDirectory.mkdirs();  
           try {  
                new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                System.out.println("Encountered issue while converting to pojo: "+e.getMessage());  
                e.printStackTrace();  
           }  
      }  


How It Works

  1. packageName defines the package name of the output POJO class.
  2. inputJson defines the JSON that needs to be converted to POJO.
  3. outputPojoDirectory is the local path where POJO files would be created.
  4. We call the convert2JSON method that we created, passing the input JSON, output path, packageName, and the output POJO class name

convert2JSON method:

      public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{  
           JCodeModel codeModel = new JCodeModel();  
           URL source = inputJson;  
           GenerationConfig config = new DefaultGenerationConfig() {  
           @Override  
           public boolean isGenerateBuilders() { // set config option by overriding method  
           return true;  
           }  
           public SourceType getSourceType(){  
       return SourceType.JSON;  
     }  
           };  
           SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());  
           mapper.generate(codeModel, className, packageName, source);  
           codeModel.build(outputPojoDirectory);  
      }  


How It Works

  1. We make an object of JCodeModel, which will be used to generate a Java class.

  2. We define the configuration for jsonschema2pojo, which lets the program know the input source file is JSON (getSourceType method)

  3. Now we pass the config to schemamapper, along with the codeModel created in step 1, which creates the JavaType from the provided JSON

  4. Finally, we call the build method to create the output class.

Full Program

package com.cooltrickshome;  
import java.io.File;  
import java.io.IOException;  
import java.net.MalformedURLException;  
import java.net.URL;  
import org.jsonschema2pojo.DefaultGenerationConfig;  
import org.jsonschema2pojo.GenerationConfig;  
import org.jsonschema2pojo.Jackson2Annotator;  
import org.jsonschema2pojo.SchemaGenerator;  
import org.jsonschema2pojo.SchemaMapper;  
import org.jsonschema2pojo.SchemaStore;  
import org.jsonschema2pojo.SourceType;  
import org.jsonschema2pojo.rules.RuleFactory;  
import com.sun.codemodel.JCodeModel;  
public class JsonToPojo {  
     /**  
      * @param args  
      */  
     public static void main(String[] args) {  
          String packageName="com.cooltrickshome";  
          File inputJson= new File("."+File.separator+"input.json");  
          File outputPojoDirectory=new File("."+File.separator+"convertedPojo");  
          outputPojoDirectory.mkdirs();  
          try {  
               new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));  
          } catch (IOException e) {  
               // TODO Auto-generated catch block  
               System.out.println("Encountered issue while converting to pojo: "+e.getMessage());  
               e.printStackTrace();  
          }  
     }  
     public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{  
          JCodeModel codeModel = new JCodeModel();  
          URL source = inputJson;  
          GenerationConfig config = new DefaultGenerationConfig() {  
          @Override  
          public boolean isGenerateBuilders() { // set config option by overriding method  
              return true;  
          }  
          public SourceType getSourceType(){  
      return SourceType.JSON;  
    }  
          };  
          SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());  
          mapper.generate(codeModel, className, packageName, source);  
          codeModel.build(outputPojoDirectory);  
     }  
}  



Input JSON:

{
	"name": "Virat",
	"sport": "cricket",
	"age": 25,
	"id": 121,
	"lastScores": [
		77,
		72,
		23,
		57,
		54,
		36,
		74,
		17
	]
}


Output class generated:

package com.cooltrickshome;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "name",
    "sport",
    "age",
    "id",
    "lastScores"
})
public class Input {
    @JsonProperty("name")
    private String name;
    @JsonProperty("sport")
    private String sport;
    @JsonProperty("age")
    private Integer age;
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("lastScores")
    private List < Integer > lastScores = new ArrayList < Integer > ();
    @JsonIgnore
    private Map < String, Object > additionalProperties = new HashMap < String, Object > ();
    @JsonProperty("name")
    public String getName() {
        return name;
    }
    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }
    public Input withName(String name) {
        this.name = name;
        return this;
    }
    @JsonProperty("sport")
    public String getSport() {
        return sport;
    }
    @JsonProperty("sport")
    public void setSport(String sport) {
        this.sport = sport;
    }
    public Input withSport(String sport) {
        this.sport = sport;
        return this;
    }
    @JsonProperty("age")
    public Integer getAge() {
        return age;
    }
    @JsonProperty("age")
    public void setAge(Integer age) {
        this.age = age;
    }
    public Input withAge(Integer age) {
        this.age = age;
        return this;
    }
    @JsonProperty("id")
    public Integer getId() {
        return id;
    }
    @JsonProperty("id")
    public void setId(Integer id) {
        this.id = id;
    }
    public Input withId(Integer id) {
        this.id = id;
        return this;
    }
    @JsonProperty("lastScores")
    public List < Integer > getLastScores() {
        return lastScores;
    }
    @JsonProperty("lastScores")
    public void setLastScores(List < Integer > lastScores) {
        this.lastScores = lastScores;
    }
    public Input withLastScores(List < Integer > lastScores) {
        this.lastScores = lastScores;
        return this;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    @JsonAnyGetter
    public Map < String, Object > getAdditionalProperties() {
        return this.additionalProperties;
    }
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
    public Input withAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
        return this;
    }
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(name).append(sport).append(age).append(id).append(lastScores).append(additionalProperties).toHashCode();
    }
    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }
        if ((other instanceof Input) == false) {
            return false;
        }
        Input rhs = ((Input) other);
        return new EqualsBuilder().append(name, rhs.name).append(sport, rhs.sport).append(age, rhs.age).append(id, rhs.id).append(lastScores, rhs.lastScores).append(additionalProperties, rhs.additionalProperties).isEquals();
    }
}


Hope it helps!

JSON Java (programming language)

Published at DZone with permission of Anurag Jain, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to Polymorphism With Database Engines in NoSQL Using Jakarta NoSQL
  • JSON Handling With GSON in Java With OOP Essence
  • Proper Java Exception Handling
  • Postgres JSON Functions With Hibernate 6

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!