Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hashmap to JSON object in Java

Tags:

java

json

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

like image 970
mohan Avatar asked Aug 28 '12 08:08

mohan


People also ask

Can we convert Hashmap to object in Java?

The most traditional way of converting a hashmap to JSON object is by calling JSONObject() and then passing the hashmap. Let's take a look at an example that creates a hashmap and then prints it in JSON format.

Can we convert Map to JSON in Java?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.

Does JSON use Hashmap?

JSON is a text based object that different from HashMap.

Can we convert JSONArray to JSON object?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.


Video Answer


2 Answers

You can use:

new JSONObject(map); 

Caution: This will only work for a Map<String, String>!

Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html

like image 181
Ankur Avatar answered Sep 17 '22 17:09

Ankur


Gson can also be used to serialize arbitrarily complex objects.

Here is how you use it:

Gson gson = new Gson();  String json = gson.toJson(myObject);  

Gson will automatically convert collections to JSON arrays. Gson can serialize private fields and automatically ignores transient fields.

like image 35
rama Avatar answered Sep 17 '22 17:09

rama