I might be getting a bit tired tonight but here it goes:
I'd like to have GWT HashMap to/from JSON. How would I achieve this?
In other words, I'd like to take an HashMap, take its JSON representation, store it somewhere and get it back to its native Java representation.
Here is my quick solution:
public static String toJson(Map<String, String> map) {
    String json = "";
    if (map != null && !map.isEmpty()) {
        JSONObject jsonObj = new JSONObject();
        for (Map.Entry<String, String> entry: map.entrySet()) {
            jsonObj.put(entry.getKey(), new JSONString(entry.getValue()));
        }
        json = jsonObj.toString();
    }
    return json;
}
public static Map<String, String> toMap(String jsonStr) {
    Map<String, String> map = new HashMap<String, String>();
    JSONValue parsed = JSONParser.parseStrict(jsonStr);
    JSONObject jsonObj = parsed.isObject();
    if (jsonObj != null) {
        for (String key : jsonObj.keySet()) {
            map.put(key, jsonObj.get(key).isString().stringValue());
        }
    }
    return map;
}
                        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