How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
29 Answers
You can use:
new JSONObject(map);
Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html
-
120This only works for a String,String map and not a complex String,Object. – slott Nov 28 '13 at 13:34
-
3You are putting `Map` into `JSONObject` but how can you get this map from jsonObject? – Yubaraj Jul 16 '14 at 07:19
-
1@Yubi this might help you : http://stackoverflow.com/questions/21720759/convert-jsonobject-to-map – Hannoun Yassir Sep 12 '14 at 21:16
-
12@slott is right for older versions. Newer versions like kitkat are working fine with more complex objects like HashMap
() containing HashMap – Luismi Dec 15 '14 at 09:52() as Object. So I recommend Gson. -
-
6To convert to JSON String instead of JSON Object: `new ObjectMapper().writeValueAsString(map);` – Andrea Bergonzo Sep 19 '17 at 14:10
-
Hi, could you please edit the caution comment? it is working in newer versions as suggested by @Luismi – OHY Feb 06 '21 at 10:41
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.

- 4,206
- 6
- 41
- 54

- 2,157
- 1
- 11
- 2
-
4
-
How does your post answer the question? It is so confusing. Please mention something relevant to the question as well. – KnockingHeads Apr 26 '21 at 08:02
-
-
You can convert Map
to JSON
using Jackson
as follows:
Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
Maven Dependencies for Jackson
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
If you are using `JSONObject` library, you can convert map to `JSON` as follows:
JSONObject Library:
import org.json.JSONObject;
Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
JSONObject json = new JSONObject(map);
System.out.println(json);
Maven Dependencies for `JSONObject` :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
Hope this will help. Happy coding.

- 1,177
- 18
- 30

- 3,396
- 3
- 31
- 42
Example using json
Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
System.out.printf( "JSON: %s", json.toString(2) );
output::
JSON: {
"age": 32,
"name": "Mars",
"city": "NY"
}
You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation.

- 4,134
- 2
- 26
- 37
-
3
-
2public String toString(int radix).toString(2) is used for String representation. for more http://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java – Mohammod Hossain Dec 22 '15 at 02:24
-
18
-
26
You can just enumerate the map and add the key-value pairs to the JSONObject
Method :
private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
JSONObject jsonData = new JSONObject();
for (String key : map.keySet()) {
Object value = map.get(key);
if (value instanceof Map<?, ?>) {
value = getJsonFromMap((Map<String, Object>) value);
}
jsonData.put(key, value);
}
return jsonData;
}

- 867
- 2
- 10
- 25
-
1
-
1The Map.Entry
> entrySet() is meant for iteration of a map. Reading the keys and searching the map for each key is a suboptimal way. – Martin Apr 20 '20 at 13:42
In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
.map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
.collect(Collectors.joining(", "))+"}";

- 1,382
- 2
- 16
- 20
-
5you're not escaping... if the key or value contains `"`, this breaks – Janus Troelsen May 12 '16 at 14:15
-
1you're right, this solution has certain limitaions, nested maps is also not supported – Andrey Sarul May 17 '16 at 12:28
Underscore-java library can convert hash map or array list to json and vice verse.
import com.github.underscore.U;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("1", "a");
map.put("2", "b");
System.out.println(U.toJson(map));
// {
// "1": "a",
// "2": "b"
// }
}
}

- 2,029
- 1
- 24
- 31
Late to the party but here is my GSON adhoc writer for serializing hashmap. I had to write map of key-value pairs as json string attributes, expect one specific to be integer type. I did not want to create custom JavaBean wrapper for this simple usecase.
GSON JsonWriter class is easy to use serializer class containing few strongly typed writer.value() functions.
// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
String val = sd.get(key);
writer.name(key);
if (key.equals("UniqueID") && val!=null)
writer.value(Long.parseLong(val));
else
writer.value(val);
}
writer.endObject();
writer.close();
If none of the custom types be needed I could have just use toJson() function. gson-2.2.4.jar library is just under 190KB without any brutal dependencies. Easy to use on any custom servlet app or standalone application without big framework integrations.
Gson gson = new Gson();
String json = gson.toJson(myMap);

- 10,181
- 6
- 53
- 65
If you need use it in the code.
Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();

- 1,236
- 13
- 22
This solution works with complex JSONs:
public Object toJSON(Object object) throws JSONException {
if (object instanceof HashMap) {
JSONObject json = new JSONObject();
HashMap map = (HashMap) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(toJSON(value));
}
return json;
}
else {
return object;
}
}

- 1,060
- 1
- 13
- 24
Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.
List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);
String json = new Gson().toJson(list);
This json
produces [{"key":"value","key":"value","key":"value"}]

- 75
- 1
- 2
-
2This doesn't answer the question. It is producing JSON array, not a JSON object. And someone else has already shown us how to create a JSON object from a hashmap using `Gson`. – Stephen C Jun 07 '19 at 10:43
-
Hi @StephenC, some might looking for an example of JSON array rather than JSON Object since the top comment has already provided the best answer so far. I hope we can provide other answers related to serializing using GSON. My apologies, this answer should be posted on a different thread. – Kelly Budol Jun 09 '19 at 23:53
-
We should be writing answers for people who search properly. If we try to cater for people who can't search by posting off-topic answers, it degrades the site with "noise", and makes it harder for people who know how to search to find *relevant* answers. If you (now) agree that this Answer is in the wrong place, please just delete it. – Stephen C Jun 10 '19 at 00:06
-
2
we use Gson.
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);

- 713
- 8
- 16
Here my single-line solution with GSON:
myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);

- 2,900
- 1
- 22
- 25
For those using org.json.simple.JSONObject
, you could convert the map to Json String and parse it to get the JSONObject
.
JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));

- 649
- 11
- 24
I found another way to handle it.
Map obj=new HashMap();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
Hope this helps.
Thanks.

- 863
- 2
- 13
- 25
If you don't really need HashMap then you can do something like that:
String jsonString = new JSONObject() {{
put("firstName", user.firstName);
put("lastName", user.lastName);
}}.toString();
Output:
{
"firstName": "John",
"lastName": "Doe"
}

- 3,028
- 1
- 21
- 16
-
Well yes. However, the question asks for a way to create a JSON object *starting from a `HashMap`*, and this doesn't answer that. – Stephen C Jun 07 '19 at 10:49
-
Some people could land here from google looking for a generic solution. The above answer might help them. – Rafal Enden Jun 11 '19 at 15:08
If you are using net.sf.json.JSONObject
then you won't find a JSONObject(map)
constructor in it. You have to use the public static JSONObject fromObject( Object object )
method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.
JSONObject jsonObject = JSONObject.fromObject(myMap);

- 11,851
- 21
- 73
- 98
No need for Gson or JSON parsing libraries.
Just using new JSONObject(Map<String, JSONObject>).toString()
, e.g:
/**
* convert target map to JSON string
*
* @param map the target map
* @return JSON string of the map
*/
@NonNull public String toJson(@NonNull Map<String, Target> map) {
final Map<String, JSONObject> flatMap = new HashMap<>();
for (String key : map.keySet()) {
try {
flatMap.put(key, toJsonObject(map.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
// 2 indentSpaces for pretty printing
return new JSONObject(flatMap).toString(2);
} catch (JSONException e) {
e.printStackTrace();
return "{}";
}
}

- 2,685
- 1
- 23
- 30
I'm using Alibaba fastjson, easy and simple:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>VERSION_CODE</version>
</dependency>
and import:
import com.alibaba.fastjson.JSON;
Then:
String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize
Everything is ok.

- 493
- 6
- 9
If you are using JSR 374: Java API for JSON Processing ( javax json ) This seems to do the trick:
JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
JsonObject jsonObject = job.build();

- 10,701
- 5
- 53
- 53
Gson way for a bit more complex maps and lists using TypeToken.getParameterized method:
We have a map that looks like this:
Map<Long, List<NewFile>> map;
We get the Type using the above mentioned getParameterized method like this:
Type listOfNewFiles = TypeToken.getParameterized(ArrayList.class, NewFile.class).getType();
Type mapOfList = TypeToken.getParameterized(LinkedHashMap.class, Long.class, listOfNewFiles).getType();
And then use the Gson object fromJson method like this using the mapOfList object like this:
Map<Long, List<NewFile>> map = new Gson().fromJson(fileContent, mapOfList);
The mentioned object NewFile looks like this:
class NewFile
{
private long id;
private String fileName;
public void setId(final long id)
{
this.id = id;
}
public void setFileName(final String fileName)
{
this.fileName = fileName;
}
}
The deserialized JSON looks like this:
{
"1": [
{
"id": 12232,
"fileName": "test.html"
},
{
"id": 12233,
"fileName": "file.txt"
},
{
"id": 12234,
"fileName": "obj.json"
}
],
"2": [
{
"id": 122321,
"fileName": "test2.html"
},
{
"id": 122332,
"fileName": "file2.txt"
},
{
"id": 122343,
"fileName": "obj2.json"
}
]
}

- 380
- 5
- 11
You can use XStream - it is really handy. See the examples here
package com.thoughtworks.xstream.json.test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class WriteTest {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<String,String>();
map.add("1", "a");
map.add("2", "b");
XStream xstream = new XStream(new JettisonMappedXmlDriver());
System.out.println(xstream.toXML(map));
}
}

- 8,229
- 9
- 50
- 98
If you use complex objects, you should apply enableComplexMapKeySerialization(), as stated in https://stackoverflow.com/a/24635655/2914140 and https://stackoverflow.com/a/26374888/2914140.
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original));
Output will be:
{
"(5,6)": "a",
"(8,8)": "b"
}
import org.json.JSONObject;
HashMap<Object, Object> map = new HashMap<>();
String[] list={"Grader","Participant"};
String[] list1={"Assistant","intern"};
map.put("TeachingAssistant",list);
map.put("Writer",list1);
JSONObject jsonObject = new JSONObject(map);
System.out.printf(jsonObject.toString());
// Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}

- 4,338
- 10
- 45
- 54
You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.
Example:
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);
You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.
However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).
More information about Gson here.
Remember that the object must implement the Serializable interface.

- 481
- 1
- 6
- 19
this works for me :
import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")
println new JsonBuilder(properties).toPrettyString()

- 1,451
- 15
- 14
-
1
-
-
The code in your question is not Java. If that code really works for you then you are not using Java. Java doesn't have a "println" statement, and you can't declare a variable like that. My guess is that you are using Groovy, but I'm not sure. Either way, recommending people to use Groovy libraries instead of Java libraries in Java code ... not a good idea. – Stephen C Jun 10 '19 at 01:55
I faced a similar problem when deserializing the Response from custom commands in selenium. The response was json, but selenium internally translates that into a java.util.HashMap[String, Object]
If you are familiar with scala and use the play-API for JSON, you might benefit from this:
import play.api.libs.json.{JsValue, Json}
import scala.collection.JavaConversions.mapAsScalaMap
object JsonParser {
def parse(map: Map[String, Any]): JsValue = {
val values = for((key, value) <- map) yield {
value match {
case m: java.util.Map[String, _] @unchecked => Json.obj(key -> parse(m.toMap))
case m: Map[String, _] @unchecked => Json.obj(key -> parse(m))
case int: Int => Json.obj(key -> int)
case str: String => Json.obj(key -> str)
case bool: Boolean => Json.obj(key -> bool)
}
}
values.foldLeft(Json.obj())((temp, obj) => {
temp.deepMerge(obj)
})
}
}
Small code description:
The code recursively traverses through the HashMap until basic types (String, Integer, Boolean) are found. These basic types can be directly wrapped into a JsObject. When the recursion is unfolded, the deepmerge concatenates the created objects.
'@unchecked' takes care of type erasure warnings.

- 29
- 3
First convert all your objects into valid Strings
HashMap<String, String> params = new HashMap<>();
params.put("arg1", "<b>some text</b>");
params.put("arg2", someObject.toString());
Then insert the entire map into a org.json.JSONObject
JSONObject postData = new JSONObject(params);
Now you can get the JSON by simply calling the object's toString
postData.toString()
//{"arg1":"<b>some text<\/b>" "arg2":"object output"}
Create a new JSONObject
JSONObject o = new JSONObject(postData.toString());
Or as a byte array for sending over HTTP
postData.toString().getBytes("UTF-8");

- 2,396
- 29
- 44
-
This is saying the same thing as previous answers from years ago, without the advantage of being concise. – Stephen C Jun 07 '19 at 10:51
-
-
@StephenC "How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?" – G_V Jun 11 '19 at 10:08
-
362 people (and counting) think that https://stackoverflow.com/a/12155874/139985 answers the question. It says basically what your answer says without the frilly bits. – Stephen C Jun 11 '19 at 12:19