如何在Java中获取Javascript变量值? [英] How can I get a Javascript variable value in Java?
问题描述
在我当前的项目中,我必须从Web上读取一个JavaScript文件并从中提取一个对象。变量可能会不时变化,因此我必须阅读它而不是将其硬编码到我的Android应用程序中。
In my current project I have to read a JavaScript file from the web and extract an object from it. The variable can vary from time to time, so I have to read it instead of hard coding it into my android app.
我想要提取以下变量(和之后使用JSONObject解析字符串,这很简单):
Say I want to extract the following variable (and parse the string using JSONObject after that, which is trivial):
var abc.xyz = {
"a": {"one", "two", "three"},
"b": {"four", "five"}
}
我有这个问题。我是否必须实现一些类似编译器的扫描程序才能查找名称并获取其值,或者我可以使用一些现有工具?
I have a problem with this. Do I have to implement some compiler-like scanner just to look for the name and get its value, or there is some existing tool I can use?
JavaScript文件是并不像这个例子那么简单。它包含很多其他代码。所以一个简单的新的JSONObject()
或其他东西都不行。
The JavaScript file is not as simple as this example. It contains a lot of other code. So a simple new JSONObject()
or something will not do.
推荐答案
Java中有许多库来解析JSON。 JSON.org 上有一个列表
There are many libraries in Java to parse the JSON. There is a list on JSON.org
阅读带有Java的文件
Read the file with Java
import org.json.JSONObject;
URL url = new URL("http://example.com/foo.js");
InputStream urlInputStream = url.openStream();
JSONObject json = new JSONObject(urlInputStream.toString());
这篇关于如何在Java中获取Javascript变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!