Create a Model From JSON Response

Mercy Jemosop
2 min readJul 1, 2022

Creating a model from a json response using jsonschema2pojo

Introduction

Model Class is used to ”model” the data in your application by defining attributes and operation for the objects of each class. You can use objects of this classes as vessel to send or receive data.

Let’s take a simple example of a model class Person, it will have attributes i.e name, age. The model class should have a getter and setter methods. You can generate them manually or use annotations i.e @Getter and @Setter or use the @Data annotation which has contains @ToString ,@EqualsAndHashCode , @Getter / @Setter and @RequiredArgsConstructor.

To use all these annotation, we need to add the lambok dependency to pom.xml

<dependency>  
<groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>

This annotations makes your code clean and more readable.

@Getter @Setter
class Person{
@JsonProperty("name")
String name;
@JsonProperty("age")
Int age;
}

Json Response,it’s the payload returned from a web service from a request. Below is a sample of a Json response. This is a Get request for getting population from a country.

Here is a link to the api which is free. We will use this API for this demo.

https://countriesnow.space/api/v0.1/countries/population/cities

The sample data from the endpoint will look like:

To generate the model class from the response above. We will use the jsonschema2pojo which will auto-generate the model class.

On your browser go to this link or search jsonschema2pojo

On the source type select JSON and annotation style select jackson

click preview to generate the classes. The classes generated look like the one below depending on your response

The @JsonProperty annotation is used to map property names with JSON Key during serialization and de-serialization. It has a variaety of properties i.e

@JsonProperty(value="name", required=true,defaultValue="No name",
access= Access.READ_WRITE)
String name;

We can break down the three classes above using annotations like we have down below.

The city folder under model package/folder contains the model classes, here is a github link for the models. This is the order of the model data flow DataModel ->Datum->PopulationCount.

You can notice that knowing about the correct annotation to use helps to clean up the code and make it more readable.

It is as easy as that. Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy