Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT HashMap to/from JSON

Tags:

json

gwt

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.

like image 854
jldupont Avatar asked Sep 02 '11 01:09

jldupont


1 Answers

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;
}
like image 74
shreyas Avatar answered Oct 13 '22 13:10

shreyas