Convert Java Map to Javascript Map
java, javascript, jsp
Solution
You might be able to use the `JSONObject` class for this. It has a constructor that you pass in a `Map`. Call that and then call the `toString()` method and it should give you a JS array.
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.util.Map%29
So something like:
Map<String, String> langSel = new HashMap<String, String>();
langSel.add("en", true);
langSel.add("de", false);
langSel.add("fr", false);
JSONObject jsonObj = new JSONObject(langSel);
engine.put("langSel", jsonObj.toString());
You will need to make sure the org.json.JSONObject class is on your classpath. Either download the JAR and add to classpath manually (through Eclipse or something) or if you are using Maven use a dependency like the following:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20070829</version>
</dependency>
If you are not using Maven, you can still download the JAR from here: http://mvnrepository.com/artifact/org.json/json/20090211
Problem
I have a Java Map. I want to convert it in to JavaScript map. The java function to convert as JS map follows: ``` private Object getJSLocalizedValueMap() { Map<String, String> langSel = new HashMap<String, String>(); langSel.add("en", true); langSel.add("de", false); langSel.add("fr", false); //Now convert this map into Javascript Map NativeObject nobj = new NativeObject(); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("javascript"); for (Map.Entry<String, String> entry : langSel.entrySet()) { nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY); } engine.put("langSel", nobj); return langSel; } ``` In the JSP page's javascript the code is: ``` var langs = ${messagesJS}; ``` In Javascript, I got: ``` langs = {en=true, de=false, fr=false}; ``` instead of ``` langs = {"en":true, "de":false, "fr":false} ``` Please suggest me how to achieve this?