JIYIK CN >

Current Location:Home > Learning > PROGRAM > Java >

How to Convert Hashmap to JSON Object in Java

Author:JIYIK Last Updated:2025/04/14 Views:

This article explains how to convert a Hashmap to a JSON object in Java. We will see a detailed example of creating a hashmap and then converting it to a JSON object.

Hashmap and JSON are both very commonly used by developers as they help us create a simple structure that can be easily used to store as well as transfer data.


new JSONObject(hashmap)Convert Hashmap to JSON object

The most traditional way to convert a hashmap to a JSON object is to call JSONObject JSONObject()and then pass the hashmap.

Let's look at an example that creates a hashmap and then prints it in JSON format.

import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;

public class Main {
  public static void main(String[] args) {
    Map<String, Object> map = new HashMap();

    map.put("key1", "value1");
    map.put("key2", "value2");

    JSONObject json = new JSONObject(map);
    System.out.printf("JSON: %s", json);
  }

Output:

JSON: {"key1":"value1","key2":"value2"}

It is important to note that Map<String, Object>Map takes a string, ie key, and an object Object, ie value. This means that we can pass any valid object as a value into Map and it will be converted into a JSON object.

Here is an example that takes a string and a Arraylistas a value.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> stringArrayList = new ArrayList<>();
    stringArrayList.add("firstString");
    stringArrayList.add("secondString");
    stringArrayList.add("thirdString");

    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("stringList", stringArrayList);

    JSONObject json = new JSONObject(map);
    System.out.printf("JSON: %s", json);
  }

Output:

JSON: {"key1":"value1","key2":"value2","stringList":["firstString","secondString","thirdString"]}

JacksonLibrary to convert Hashmap to JSON object

In Java, there are some libraries that can help us convert Hashmap to JSON object and they are very flexible.

Jackson is one of these libraries that takes a Java mapand converts it into JSON format.

Let's not forget to handle that JsonProcessingException, because ObjectMapper().writeValueAsString(map)when an incompatible data format is found, an exception will be thrown.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) throws JsonProcessingException {
    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");

    String json = new ObjectMapper().writeValueAsString(map);
    System.out.printf("JSON: %s", json);
  }

Output:

JSON: {"key1":"value1","key2":"value2"}

GSONLibrary to convert Hashmap to JSON object

GsonThe library is one of the most commonly used libraries to convert hashmap to JSON object. It provides easy methods to handle our hashmap and JSON.

GsonThe class has a method toJsonTreewhich takes our Map and converts it into a JSON tree. But since we want a JSON object, we can use toJSONObject()to make the JSON tree into a JSON object.

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");

    Gson gson = new Gson();
    JsonObject json = gson.toJsonTree(map).getAsJsonObject();

    System.out.printf("JSON: %s", json);
  }

Output:

JSON: {"key1":"value1","key2":"value2"}

Previous:How to sort a Map by value in Java

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Get JSON object from URL in PHP

Publish Date:2025/04/12 Views:64 Category:PHP

This article explains how to get a JSON object from a URL in PHP. file_get_contents() Get JSON object from URL in PHP using function We can use the README.mdl file_get_contents() and README.mdl json_decode() to get a JSON object from a URL.

Importing JSON files into MongoDB

Publish Date:2025/04/10 Views:180 Category:MongoDB

This post will discuss how to quickly and easily import all three file formats (JSON, CSV, and TSV) into your MongoDB database instance. So without further ado, let’s get started. What is MongoDB MongoDB is a NoSQL (non-relational) databa

JSONB in PostgreSQL

Publish Date:2025/04/09 Views:199 Category:PostgreSQL

JSONB is a decomposed binary format for storing JSON data. If you follow Google Trends or do some research, you'll see that JSON is becoming increasingly popular in the development world. Nowadays, NoSQL can store JSON data by default. It i

Importing JSON files into Vue

Publish Date:2025/02/26 Views:101 Category:Vue

Vue.js is a popular JavaScript framework that can quickly build single-page applications (SPA). In Vue.js, we can use JSON files to store data, which is very useful in development. This article will introduce how to introduce JSON files in V

在 Pandas 中加载 JSON 文件

Publish Date:2024/04/21 Views:110 Category:Python

本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial