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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object
  • Writing DTOs With Java8, Lombok, and Java14+
  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps

Trending

  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • MCP Servers: The Technical Debt That Is Coming
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • Scaling Microservices With Docker and Kubernetes on Production
  1. DZone
  2. Coding
  3. Languages
  4. Easy Mapping JSON to Java Objects Using Jackson

Easy Mapping JSON to Java Objects Using Jackson

Mapping JSON to Java objects just got a lot easier with Jackson.

By 
Pimchaya Wongrukun user avatar
Pimchaya Wongrukun
·
Jan. 20, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
29.1K Views

Join the DZone community and get the full member experience.

Join For Free
Mapping JSON to Java objects just got a lot easier with Jackson.

Introduction

Jackson is a very popular and efficient Java-based library used to map JSON into Java objects, and vice versa. In this article, I will demonstrate how easy it is to use Jackson for retrieving data in the JSON response received from REST API and save it to a CSV file.

I will be retrieving the financial data from Elektron Data Platform (EDP), which provides access to Refinitiv various sets of data and will be using historical pricing for the sample.

You may also like: Processing JSON With Jackson

Image title









Pre-Requisite

1. EDP access credentials (username, password, and clientId), which can retrieve historical pricing events data. You can contact Refinitiv representatives to acquire username and password and use that to generate clientId at App key Generator.

2. The EDPToken helper class is used to obtain an access token, which is required before any data requests. You can simply follow this article: Easy Obtaining Token from EDP Gateway in Java.

How it Works

The overview of the process is the following diagram:

Image title







Firstly, you need to have a Java class (the top gray box in the diagram), which matches the format of the JSON data response from EDP. The steps to create the Java class are described in Creating Java Class which matches JSON Response from EDP section below.

Then, you can use Jackson  ObjectMapper to read the Java class and JSON response received from the REST API to create a Java object representing the parsed JSON. Then, you can call methods of the Java object to get any values of parsed JSON.

In my application, I will get the values of data key, name, and type in headers key by calling the methods of HistoricalPricingEvent object. The snipped source code is shown below:

Java




x
14


 
1
//Jackson ObjectMapper reads HistoricalPricingEvents class and historical pricing events JSON response
2
//to create an object representing the parsed JSON.
3
HistoricalPricingEvent eventsData = new ObjectMapper().readerFor( HistoricalPricingEvent.class).readValue(jsonResp);
4
//get the values of data key in the object
5
List<List<String>> data = (List<List<String>>)eventsData.getData();
6
//Get the values of headers key in the object
7
List<Header> headers= eventsData.getHeaders();
8
//Get the values of name and type key in headers
9
Iterator<Header> hiterator = headers.iterator();
10
while(hiterator.hasNext()) {
11
   Header aheader = (Header)hiterator.next();
12
   String name = aheader.getName();
13
   String type = aheader.getType();
14
}



The HistoricalPricingEvent class can be generated by http://www.jsonschema2pojo.org/.

The complete application source code, including theHistoricalPricingEvent class, can be found on GitHub.

Creating a Java Class to Match the JSON Response From EDP

Instead of writing the full Java class manually, I will use the http://www.jsonschema2pojo.org/ page, which can generate a Java class with Jackson annotation from JSON and JSON schema. Please follow these steps to create a Java class from the JSON schema of historical pricing events data JSON response.

1. Go to API Playground and find the /data/historical-pricing/ service. Then, select the /views/events/{universe} path.

Image title






2. Select the Swagger menu to download the JSON schema file.

Image title








3. Open the schema file. Under /views/events/{universe}, find the successful response (200 HTTP status code) that contains data. The response refers to the value in /definitions/historicalPricingData path.

Image title










     Copy the value in the /definitions/historicalPricingData path:

Paste the value in the text box on http://www.jsonschema2pojo.org/

4. Look into the value in the text box, find $ref, which refers to /definitions/status path:

Copy the value in the /definitions/status path that $ref refers to:

Replace $ref line with the copied value:

The complete JSON schema in the text box (the step 3–4) is dataResponseJson.zip.

5. Set Package and Class name e.g. com.java.response and HistoricalPricingEvent respectively. At Source type, select JSON Schema. The Class name is the name of the Java class that matches the format of JSON schema.

6. Click Zip button. Then, the Java classes are generated and compressed in the zip file. Finally, the zip file name is shown:

Click at the file name to download.

When you uncompress the zip file, you will see the Java class file (HistoricalPricingEvent) and the related classes as below:

Compile and Run Application

Before you can compile and run the application, you have to set the CLASSPATH to point to Apache Http Components, JSON in java, Jackson Core, Jackson Annotations, and Jackson Databind like an example on Windows machine below:

Java




xxxxxxxxxx
1


 
1
set CLASSPATH=C:\thirdPartyJars\httpcomponents-client-4.5.9\lib\commons-codec-1.11.jar;C:\thirdPartyJars\httpcomponents-client-4.5.9\lib\commons-logging-1.2.jar;C:\thirdPartyJars\httpcomponents-client-4.5.9\lib\httpclient-4.5.9.jar;C:\thirdPartyJars\httpcomponents-client-4.5.9\lib\httpcore-4.4.11.jar;C:\thirdPartyJars\JsonInJava\json-20180813.jar;C:\thirdPartyJars\commons-cli-1.4\commons-cli-1.4.jar;C:\thirdPartyJars\Jackson\jackson-annotations-2.9.9.jar;C:\thirdPartyJars\Jackson\jackson-core-2.9.9.jar;C:\thirdPartyJars\Jackson\jackson-databind-2.9.9.jar



The Java command line to request the latest five quote events of item name “THB=,” which is Thai Baht is below:

Java




xxxxxxxxxx
1


 
1
java -classpath %CLASSPATH%;. com.java.HistoricalPricingEventsRequestor -user <EDP username> -clientId <clientId> -rics THB= -events quote -count 5



The console will display the following once successful:

You can now check the historical pricing events data in a CSV file like an example below:

Summary

This is just a sample to explain how to use Jackson to map JSON to Java objects. Then, you can easily manage the Java objects in various ways. It also suggests http://www.jsonschema2pojo.org/, which can generate the Java class from the JSON response schema. Jackson requires this Java class for parsing a JSON response into an object of this Java class. This can be more automated especially with the schema file access and update, which can be found in APIDocs for other APIs.

Further Reading

Processing JSON With Jackson

Jackson Annotations for JSON: Deserialization

JSON Java (programming language) Jackson (API) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object
  • Writing DTOs With Java8, Lombok, and Java14+
  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps

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!