You can also try something like this with Gson Library:
package com.stackoverflow.works;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/*
* @Author: sarath_sivan
*/
public class MapToJsonConverter {
/*
* @Description: Method to convert Map to JSON String
* @param: map Map<String, String>
* @return: json String
*/
public static String convert(Map<String, String> map) {
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}
/*
* @Description: Method to convert JSON String to Map
* @param: json String
* @return: map Map<String, String>
*/
public static Map<String, String> revert(String json) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
return map;
}
/*
* @Description: Method to print elements in the Map
* @param: map Map<String, String>
* @return: void
*/
public static void printMap(Map<String, String> map) {
for (String key : map.keySet()) {
System.out.println("map.get(\"" + key + "\") = " + map.get(key));
}
}
/*
* @Description: Method to print the JSON String
* @param: json String
* @return: void
*/
public static void printJson(String json) {
System.out.println("json = " + json);
}
/*
* @Description: Main method to test the JSON-MAP convert/revert logic
*/
public static void main(String[] args) {
Map<String, String> paymentCards = new HashMap<String, String>();
paymentCards.put("card_switch", "Master");
paymentCards.put("issuing_bank", "ICCI");
paymentCards.put("card_Type", "DebitCard");
String json = convert(paymentCards); //converting Map to JSON String
System.out.println("Map to JSON String");
System.out.println("******************");
printJson(json);
System.out.println();
paymentCards = revert(json); //converting JSON String to Map
System.out.println("JSON String to Map");
System.out.println("******************");
printMap(paymentCards);
}
}
The output look like this:

You can also try something like this with Gson Library:
package com.stackoverflow.works;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/*
* @Author: sarath_sivan
*/
public class MapToJsonConverter {
/*
* @Description: Method to convert Map to JSON String
* @param: map Map<String, String>
* @return: json String
*/
public static String convert(Map<String, String> map) {
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}
/*
* @Description: Method to convert JSON String to Map
* @param: json String
* @return: map Map<String, String>
*/
public static Map<String, String> revert(String json) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
return map;
}
/*
* @Description: Method to print elements in the Map
* @param: map Map<String, String>
* @return: void
*/
public static void printMap(Map<String, String> map) {
for (String key : map.keySet()) {
System.out.println("map.get(\"" + key + "\") = " + map.get(key));
}
}
/*
* @Description: Method to print the JSON String
* @param: json String
* @return: void
*/
public static void printJson(String json) {
System.out.println("json = " + json);
}
/*
* @Description: Main method to test the JSON-MAP convert/revert logic
*/
public static void main(String[] args) {
Map<String, String> paymentCards = new HashMap<String, String>();
paymentCards.put("card_switch", "Master");
paymentCards.put("issuing_bank", "ICCI");
paymentCards.put("card_Type", "DebitCard");
String json = convert(paymentCards); //converting Map to JSON String
System.out.println("Map to JSON String");
System.out.println("******************");
printJson(json);
System.out.println();
paymentCards = revert(json); //converting JSON String to Map
System.out.println("JSON String to Map");
System.out.println("******************");
printMap(paymentCards);
}
}
The output look like this:

Have a look at example 1.4 on this page http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object_-_Using_Map_and_streaming:
Map obj=new LinkedHashMap();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
StringWriter out = new StringWriter();
JSONValue.writeJSONString(obj, out);
String jsonText = out.toString();
System.out.print(jsonText);
Try this :
public static class User
{
public User(int userId, int roleId)
{
this.userId = userId;
this.roleId = roleId;
}
private int userId;
private int roleId;
public int getUserId()
{
return userId;
}
public int getRoleId()
{
return roleId;
}
public void setUserId(int userId)
{
this.userId = userId;
}
public void setRoleId(int roleId)
{
this.roleId = roleId;
}
}
Test :
Map<String, Object> responseObj = new HashMap<String, Object>();
List<User> userList = new ArrayList<User>();
userList.add(new User(1, 1));
userList.add(new User(2, 2));
responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);
System.out.println(new JSONObject(responseObj));
Prints :
{"approvers":[{"userId":1,"roleId":1},{"userId":2,"roleId":2}],"canApprove":true}
(formatted)
You can try to use JSONObject to parse the map to JSON.
The maven dependency is:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
later create a new JSON object and pass the map
JSONObject obj = new JSONObject(responseObj);
and return the object to this web client.
In recursive way:
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Using Gson, you can do the following:
Map<String, Object> retMap = new Gson().fromJson(
jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
Using the GSON library:
import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;
Use the following code:
Type mapType = new TypeToken<Map<String, Map>>(){}.getType();
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
Parse the JSONObject and create HashMap
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}
Tested output:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
You can use Google's Gson library to convert json to Hashmap. Try below code
String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());