How to convert hashmap to JSON object in Java

To convert a hashmap to a JSON object in Java, you can use the org.json library. Here's an example:

import org.json.JSONObject;

HashMap<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("num", 42);
map.put("bool", true);

JSONObject json = new JSONObject(map);
System.out.println(json);

This will print the following JSON object:

{"key":"value","num":42,"bool":true}

You can also use other JSON libraries, such as Google's Gson or FasterXML's Jackson, to convert a hashmap to a JSON object.

Here's an example using Gson:

import com.google.gson.Gson;

HashMap<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("num", 42);
map.put("bool", true);

Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);

And here's an example using Jackson:

import com.fasterxml.jackson.databind.ObjectMapper;

HashMap<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("num", 42);
map.put("bool", true);

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
System.out.println(json);