简体   繁体   English

将Java Map转换为Javascript Map

[英]Convert Java Map to Javascript Map

I have a Java Map. 我有一个Java Map。 I want to convert it in to JavaScript map. 我想将其转换为JavaScript地图。

The java function to convert as JS map follows: 要转换为JS映射的java函数如下:

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: 在JSP页面的javascript中,代码是:

var langs = ${messagesJS};

In Javascript, I got: 在Javascript中,我得到了:

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 JSONObject class for this. 您可能可以使用JSONObject类。 It has a constructor that you pass in a Map . 它有一个你在Map传递的构造函数。 Call that and then call the toString() method and it should give you a JS array. 调用它,然后调用toString()方法,它应该给你一个JS数组。

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.util.Map%29 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. 您需要确保org.json.JSONObject类在您的类路径中。 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: 下载JAR并手动添加到类路径(通过Eclipse或其他东西),或者如果您使用Maven,请使用如下所示的依赖项:

  <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 如果您没有使用Maven,您仍然可以从这里下载JAR: http//mvnrepository.com/artifact/org.json/json/20090211

Instead of below line 而不是线下

langSel.add("en", true);

use this line 使用这一行

langSel.add("\"en\"", true);

Try this it might helpful. 试试这可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM