creating Hashmap from a JSON String
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());
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}
public class JsonMapExample {
public static void main(String[] args) {
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
{phonetype=N95, cat=WP}
You can see this link it's helpful http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
You could use Gson library
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);