如何将Java Map转换为基本的Javascript对象?

时间:2011-09-22 18:07:51

标签: java javascript rhino

我开始在Java 6中使用动态rhinoscript功能,供更有可能了解Javascript而不是Java的客户使用。

将Map(关联数组,javascript obj,等等)传递给Javascript的最佳方法是什么,以便脚本编写者可以使用标准的Javascript点表示法来访问值?

我目前正在将java.util.Map值传递给脚本,但是脚本编写者必须编写“map.get('mykey')”而不是“map.mykey”。

基本上,我想做与this question.

相反的事情

4 个答案:

答案 0 :(得分:12)

我采用了Java NativeObject方法,这就是我所做的......

// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");

// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
    nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}

// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);

// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");

答案 1 :(得分:6)

我正在使用一个将Map转换为javascript哈希对象的实用程序类:

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.mozilla.javascript.Scriptable;
public class MapScriptable implements Scriptable, Map {
    public final Map map;
    public MapScriptable(Map map) {
        this.map = map;
    }
    public void clear() {
        map.clear();
    }
    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }
    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }
    public Set entrySet() {
        return map.entrySet();
    }
    public boolean equals(Object o) {
        return map.equals(o);
    }
    public Object get(Object key) {
        return map.get(key);
    }
    public int hashCode() {
        return map.hashCode();
    }
    public boolean isEmpty() {
        return map.isEmpty();
    }
    public Set keySet() {
        return map.keySet();
    }
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }
    public void putAll(Map m) {
        map.putAll(m);
    }
    public Object remove(Object key) {
        return map.remove(key);
    }
    public int size() {
        return map.size();
    }
    public Collection values() {
        return map.values();
    }
    @Override
    public void delete(String name) {
        map.remove(name);
    }
    @Override
    public void delete(int index) {
        map.remove(index);
    }
    @Override
    public Object get(String name, Scriptable start) {
        return map.get(name);
    }
    @Override
    public Object get(int index, Scriptable start) {
        return map.get(index);
    }
    @Override
    public String getClassName() {
        return map.getClass().getName();
    }
    @Override
    public Object getDefaultValue(Class<?> hint) {
        return toString();
    }
    @Override
    public Object[] getIds() {
        Object[] res=new Object[map.size()];
        int i=0;
        for (Object k:map.keySet()) {
            res[i]=k;
            i++;
        }
        return res;
    }
    @Override
    public Scriptable getParentScope() {
        return null;
    }
    @Override
    public Scriptable getPrototype() {
        return null;
    }
    @Override
    public boolean has(String name, Scriptable start) {
        return map.containsKey(name);
    }
    @Override
    public boolean has(int index, Scriptable start) {
        return map.containsKey(index);
    }
    @Override
    public boolean hasInstance(Scriptable instance) {
        return false;
    }
    @Override
    public void put(String name, Scriptable start, Object value) {
        map.put(name, value);
    }
    @Override
    public void put(int index, Scriptable start, Object value) {
        map.put(index, value);
    }
    @Override
    public void setParentScope(Scriptable parent) {}
    @Override
    public void setPrototype(Scriptable prototype) {}
}

样品:

import java.util.HashMap;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;

public class MapScriptableMain {
    public static void main(String[] args) {
        Map src=new HashMap();
        src.put("foo", 2);
        src.put("bar", 3);
        MapScriptable m=new MapScriptable(src);
        Context c=Context.enter();
        ScriptableObject scope = c.initStandardObjects();
        ScriptableObject.putProperty(scope, "m", m);
        String source = "m.baz=m.foo+m.bar;";
        Object a=c.evaluateString(scope, source, "TEST", 1, null);
        System.out.println(a); // 5.0
        System.out.println(src.get("baz")); // 5.0;
    }
}

答案 2 :(得分:3)

在确定SimpleScriptContext只会占用Map对象并因此迫使您在JavaScript中使用Java方法之后,这就是我所做的。

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("test", "hello world!");

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Object eval = engine.eval("var map = " + new Gson().toJson(myMap) + ";\n" 
    + "println(map.test);");

打印出来

hello world!

答案 3 :(得分:2)

您只需手动将对象编码为JSON,或使用Jacksongson等库。如你所说,这是该问题的确切对话,该问题的作者对JSON符号不满意:))

您需要发送到浏览器的内容基本上是这样的:

var someObject = { "key1": "value1", "key2": "value2", ... }

然后javascript开发人员可以访问:someObject.key2