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?
You might be able to use the
JSONObjectclass for this. It has a constructor that you pass in aMap. Call that and then call thetoString()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:
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:
If you are not using Maven, you can still download the JAR from here: http://mvnrepository.com/artifact/org.json/json/20090211