JSON转为java类:
public class JSON2Java {
private static final ScriptEngine jsonParser;
static
{
try
{
String init = read(Tools.class.getResource("json2java.js"));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(init);
jsonParser = engine;
}
catch (Exception e)
{
// Unexpected
throw new AssertionError(e);
}
}
public static Object parseJSON(String json)
{
try
{
Bindings bindings = new SimpleBindings();
String eval = "var tmp = (" + json + ");var o = new java.util.concurrent.atomic.AtomicReference(tmp.toJava());";
jsonParser.eval(eval, bindings);
AtomicReference ret = (AtomicReference)bindings.get("o");
return ret.get();
}
catch (ScriptException e)
{
throw new RuntimeException("Invalid json", e);
}
}
}
我们编写一个 json2java.js 文件,这里面提供了一些 toJava 的函数,用于将 JSON 的对象转成对应的 Java 类型。
Object.prototype.toJava = function() {
var m = new java.util.HashMap();
for (var key in this)
if (this.hasOwnProperty(key))
m.put(key, this[key].toJava());
return m;
};
Array.prototype.toJava = function() {
var l = this.length;
var a = new java.lang.reflect.Array.newInstance(java.lang.Object, l);
for (var i = 0;i < l;i++)
a[i] = this[i];
return a;
};
String.prototype.toJava = function() {
return new java.lang.String(this);
};
Boolean.prototype.toJava = function() {
return java.lang.Boolean.valueOf(this);
};
Number.prototype.toJava = function() {
return java.lang.Integer(this);
};
解析操作:
Bindings bindings = new SimpleBindings();
String eval = "var tmp = (" + json + ");var o = new AtomicReference(tmp.toJava());";
jsonParser.eval(eval, bindings);
AtomicReference ret = (AtomicReference)bindings.get("o");
return ret.get();
初始化安装:
String init = read(Tools.class.getResource("json2java.js"));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(init);
jsonParser = engine;
具体参看:https://gist.github.com/1521692