Home > Java > javaTutorial > How to Convert a Java HashMap to a JSONObject and JSON String?

How to Convert a Java HashMap to a JSONObject and JSON String?

Patricia Arquette
Release: 2024-12-04 08:24:13
Original
581 people have browsed it

How to Convert a Java HashMap to a JSONObject and JSON String?

Converting HashMap to JSONObject and JSON String in Java

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);
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template