GWT HashMap to / from JSON

I may be a little tired today, but here it is:

I would like to have a GWT HashMap in / out of JSON. How can i achieve this?

In other words, I would like to take a HashMap , take its JSON representation, save it somewhere and return it to my own Java view.

+6
source share
2 answers

Not the most optimized, but easy to code: use JSONObject .

Iterate over your records and put them into a JSONObject (converting each value to a JSONValue appropriate type), then call toString to get a JSON view.

For parsing, return JSONObject back using JSONParser , then go through the keySet , get values ​​and put them on your map (after JSONValue s)

But be careful with the keys you use! You cannot use any key as a property name in JS; and JSON processing in the browser always involves going through a JS object (or the JSON parser itself, which will not do the same)

+3
source

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; } 
+10
source

Source: https://habr.com/ru/post/896456/


All Articles