问题描述
JSONata是一种用于查询和转换JSON数据结构的表达式语言。
JSONata is an expression language designed to query and transform JSON data structures.
我发现JSONata的当前实现仅在Javascript中。 ()
I find that current implementations of JSONata are in Javascript only. (https://github.com/jsonata-js/jsonata)
我想在我的Java代码中使用JSONata。它将使用Java操作JSON文档变得更加容易。
I want to use JSONata in my Java code. It'll make life much easier to manipulate JSON documents in Java.
一种可能的方法是使用javax.script包下的标准Java类与Javascript交互基于JSONata的实现。
A possible way could be to use the standard Java classes under javax.script package to interact with the Javascript-based JSONata implementation.
有没有人这样做过?是否有任何示例代码来演示如何实现这一目标?
Has anyone already done this? Is there any sample code to demonstrate how this can be achieved?
是否有人在Java中实现了使用JSONata的其他机制?
Has anyone implemented other mechanisms of using JSONata in Java?
推荐答案
以下代码段显示了如何使用嵌入式JavaScript引擎从Java调用JSONata处理器...
The following snippet shows how you could invoke the JSONata processor from Java using the embedded JavaScript engine...
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Invocable inv = (Invocable) engine;
FileReader jsonata = new FileReader("jsonata.js");
// load the JSONata processor
engine.eval(jsonata);
// read and JSON.parse the input data
byte[] sample = Files.readAllBytes(Paths.get("sample.json"));
engine.put("input", new String(sample));
Object inputjson = engine.eval("JSON.parse(input);");
// query the data
String expression = "$sum(Account.Order.Product.(Price * Quantity))"; // JSONata expression
Object expr = inv.invokeFunction("jsonata", expression);
Object resultjson = inv.invokeMethod(expr, "evaluate", inputjson);
// JSON.stringify the result
engine.put("resultjson", resultjson);
Object result = engine.eval("JSON.stringify(resultjson);");
System.out.println(result);
在这个例子中,jsonata.js文件已经从JSONata GitHub repo中下拉了来自的发票示例代码。
In this example, the jsonata.js file has been pulled down from the JSONata GitHub repo as well as the 'Invoice' sample code from try.jsonata.org.
处理错误需要额外的代码,但这给出了一般的想法。
Extra code would be needed to handle errors, but this gives the general idea.
这篇关于如何在Java中使用JSONata?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!