How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
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.
We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.
JSON is a text based object that different from HashMap.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With