Converting a HashMap to a JSON object in Java is a straightforward process. To achieve this, you can utilize the JSONObject provided by the JSON-Java library.
Firstly, instantiate a new JSONObject by passing in the HashMap as an argument:
JSONObject jsonObject = new JSONObject(map);
The resulting JSONObject will contain key-value pairs corresponding to the HashMap's entries. Incidentally, JSON-Java also offers other useful functions that you can explore by referring to its documentation.
To further convert the JSONObject to a JSON string, simply call the toString() method:
String jsonString = jsonObject.toString();
You can then work with the resulting JSON string as necessary.
The above is the detailed content of How to Convert a Java HashMap to a JSONObject and JSON String?. For more information, please follow other related articles on the PHP Chinese website!