🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Overview
Converting JSON strings to Java objects (and vice versa) is a frequent need in modern Java applications, especially when dealing with RESTful web services. In this tutorial, we'll look at how to use the Jackson library to convert a JSON string representing a user into a Java Map.
Check out all the Java Jackson JSON tutorials and examples: 50+ Java Jackson JSON Tutorials with Examples
2. Development Steps
1. Set up a new Maven project.
2. Add the required Jackson dependencies.
3. Create a sample JSON string representing a user.
4. Utilize Jackson's ObjectMapper to convert this string into a Map.
5. Display the contents of the Map.
3. Create a Maven Project
There are different ways to create a simple Maven project:
Create a Simple Maven Project using the Command Line Interface
Create a Simple Maven Project using Eclipse IDE
Create a Simple Maven Project using IntelliJ IDEA
4. Maven Dependencies
Open the pom.xml file, and add the following Jackson data binding dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
5. Example 1: Convert JSON string to Map in Java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class MainApp {
public static void main(String[] args) {
// Sample JSON string
String jsonStr = "{\"id\":1,\"name\":\"Jane Smith\",\"email\":\"jane.smith@example.com\"}";
// Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string to Map
Map<String, Object> map = mapper.readValue(jsonStr, Map.class);
// Display the map
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
id: 1 name: Jane Smith email: jane.smith@example.com
Code Explanation:
1. We initiate with a sample JSON string that represents a user.
2. Next, we create an instance of the ObjectMapper class.
3. Using the readValue() method of ObjectMapper, the JSON string is converted into a Map.
4. The map's contents are displayed using a simple loop.
Note: The generic Map.class was used, implying the keys are Strings, but values are treated as Objects. This allows for flexibility in handling different data types within the JSON string.
6. Example 2: Convert Complex JSON string to Map in Java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonToMapExample {
public static void main(String[] args) {
try {
// Example of complex JSON string
String jsonString = "{"
+ "\"name\":\"John\","
+ "\"age\":30,"
+ "\"address\":{"
+ " \"street\":\"123 Main St\","
+ " \"city\":\"Springfield\","
+ " \"zipcode\":\"12345\""
+ "},"
+ "\"phoneNumbers\":[\"123-456-7890\",\"987-654-3210\"]"
+ "}";
// Create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Convert JSON string to Map
Map<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
// Print the Map in an organized manner
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
System.out.println(entry.getKey() + " = ");
Map<String, String> nestedMap = (Map<String, String>) entry.getValue();
for (Map.Entry<String, String> nestedEntry : nestedMap.entrySet()) {
System.out.println(" " + nestedEntry.getKey() + " = " + nestedEntry.getValue());
}
} else if (entry.getValue() instanceof List) {
System.out.println(entry.getKey() + " = " + entry.getValue());
} else {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
name = John
age = 30
address =
street = 123 Main St
city = Springfield
zipcode = 12345
phoneNumbers = [123-456-7890, 987-654-3210]
7. Conclusion
Jackson offers a powerful and efficient means of converting between JSON strings and Java Maps, allowing for flexible data processing within Java applications. This functionality is especially valuable when handling dynamic or unpredictable JSON structures.
Check out all the Java Jackson JSON tutorials and examples: 50+ Java Jackson JSON Tutorials with Examples
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment