Convert Java HashMap to JSON

Posted on 18-02-2013 12:45 by graham
This tutorial shows how you can convert a Java map (e.g. a HashMap) to JSON string.

Conversion using JSONValue class


We will perform the conversion using the org.json.simple.JSONValue class. The code is in fact very simple:
Map<String, Integer> ageMap = new HashMap<String, Map>();
ageMap.put ("Jane", 25);
ageMap.put ("Carl", 31);
String jsonString = JSONValue.toJSONString(ageMap);

As a result, you will get a JSON string of the following format:
{
"Jane": 25,
"Carl": 31
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems