在java中如何解析json?fastjson?jackson?那未免太无趣了
其实我们可以试试ScriptEngine
public class NashornTest {
private static String json = "[{name:'A',age:'18'},{name:'B',age:'19'},{name:'C',age:'30'}]";
private static String script =
"function parse(json){" +
" var names = new Array();" +
" for(var i in json){" +
" names.push(json[i].name);" +
" }" +
" return names;" +
"};" +
"parse(" + json + ");";
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName( "JavaScript" );
Map<String,String> result = (Map<String,String>)engine.eval(script);
result.forEach((k,v) -> System.out.println(v));
}
}
输出:
A
B
C
代码中使用了 lambda