Horje
How to Convert a HashSet to JSON in Java?

In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Java.

Steps to convert a HashSet to JSON in Java

Below are the steps and implementation of converting a HashSet to JSON in Java with Jackson.

Step 1: Create a Maven Project

Open any preferred IDE and Create a new Maven project. Here, we are using IntelliJ IDEA. So, we can do this by selecting File -> New -> Project.. -> Maven and following the wizard.

Project Creation

Project Structure:

Below is the project structure that we have created.

Project Structure

Step 2: Add Jackson Dependency to the pom.xml

Now, we will add Jackson dependency to pom.xml file.

XML

<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <modelVersion>4.0.0</modelVersion>
  
    <groupId>org.example</groupId>
    <artifactId>HashSet</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
  
</project>

Step 3: Add logic of Conversion of a HashSet to JSON String

Below is the implementation to convert a HashSet to JSON with Jackson.

Java

// Java Program for Conversion of a HashSet to JSON String
package org.example;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.util.HashSet;
  
// Main Class
public class Main {
      // main function
    public static void main(String[] args)
    {
        // Create a HashSet of courses
        HashSet<String> courses = new HashSet<>();
        courses.add("Java");
        courses.add("Python");
        courses.add("C++");
  
        // Create ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
  
        try {
            // Create ObjectWriter with default pretty printer
            ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
              
            // Convert HashSet to JSON
            String jsonData = writer.writeValueAsString(courses);
              
            // Print JSON Data
            System.out.println(jsonData);
        }
        catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Explanation of the above code:

  • It creates a HashSet of courses – Java, Python, C++
  • Jackson ObjectMapper is used to convert Java objects to JSON.
  • ObjectWriter is used to format the JSON with proper indentation.
  • HashSet is converted to a JSON string using ObjectWriter.
  • The JSON string is printed to the output.

Output:

JSON String output




Reffered: https://www.geeksforgeeks.org


Java

Related
Extract a Substring Between Two Characters in a String in Java Extract a Substring Between Two Characters in a String in Java
How to Convert an ArrayList Containing Integers to Primitive Int Array? How to Convert an ArrayList Containing Integers to Primitive Int Array?
Array with Constant Time Insertions and Deletions in Java Array with Constant Time Insertions and Deletions in Java
How to Create a TreeMap in Java and Add Key-Value Pairs in it? How to Create a TreeMap in Java and Add Key-Value Pairs in it?
How to Format Seconds in Java? How to Format Seconds in Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13