I am using Rhino to communicate between Java and JavaScript.
I call a JavaScript function via Rhino and this function takes an argument which must be a JSON-object. How do i parse Java-object to JSON and pass it to JavaScript in my case?
Java-code:
try {
engine.eval(fileReader);
Invocable invocableEngine = (Invocable) engine;
Object o = invocableEngine.invokeFunction("f", MyObject json);
System.out.println(o);
} catch (ScriptException ex) {
ex.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
JavaScript-Code:
function f(json){
var id = json.id;
return id;
}
I haven't used rhino, but for conversion of Java objects/collections to json I use the google library gson.
Back when I was using Rhino I just converted my Java-JSON-Object(org.json.JSONObject) to String and passed them as function parameter to a javascript function existing in the rhino scope.
String itemDatagram = jsonItemDatagram.toString;
String code = "inside.js.scope.aFunction(" + itemDatagram + ");";
The code String object would then have to be evaluated by Rhino. The String object automagically becomes a Javascript object inside the js scope(on the Rhino side). And since JSON is just a subset of javascript objects this should be what you want.
Related
After looking at many examples available on Stack Overflow, I still haven't been able to figure out how to make it work out in my case yet. So, could you please provide me with some guidelines wherever possible? Specifically, I have already built a JSON array containing a tag and a JSON object, which should look like below when being posted (including the square brackets "[]"):
[
"location",
{
"coordinateA":12.45817,
"coordinateB":23.9195856
}
]
The corresponding JAVA code is as follows:
JSONObject CoordinatesFinalObj = new JSONObject();
JSONObject Location = new JSONObject();
try {
CoordinatesFinalObj.put("location-one", LocationOne);
} catch (JSONException e) {
e.printStackTrace();
}
try {
LocationOne.put("coordinateA", 12.45817);
LocationOne.put("coordinateB", 23.9195856);
} catch (JSONException e) {
e.printStackTrace();
}
When I POST-ed such the JSON array to our server using Volley JSON Object Request, it always returned the error 417. I actually did something similar by posting a Python array with a tag and a JSON object inside without any problems. And there are no special requirements of the http request header as imposed by our server.
JsonObjectRequest CoordinatesJsonObjectReq = new JsonObjectRequest(Request.Method.POST,
url, **CoordinatesFinalObj**, new Response.Listener<JSONObject>()...).
So, my question here is: Is Volley JSON Object Request a good fit for this purpose or I shall simply switch to use a string-based POST method (e.g. HttpURLConnection though it is a deprecated module). I am very confused why it is not working here...
I was creating a simple android application in which I am converting an object to String. How can I re-convert the object from the string?
I am converting my object to String using the following line of code.
String convertedString = object.toString();
You can't**, because that is not what the toString method is for. It's used to make a readable representation of your Object, but it's not meant for saving and later reloading.
What you are looking for instead is Serialization. See this tutorial here to get started:
http://www.tutorialspoint.com/java/java_serialization.htm
** Technically you could, but you shouldn't.
You can do it in two ways:
Java Serialization
Using Gson library (more simple), remember the the purpose of this lib is to convert simply json to object and viceversa when working with REST services.
Hope it helps
You can use Serialization to convert object to string and vise versa:
String serializedObject = "";
// serialize the object
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(myObject);
so.flush();
serializedObject = bo.toString();
} catch (Exception e) {
System.out.println(e);
}
// deserialize the object
try {
byte b[] = serializedObject.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
MyObject obj = (MyObject) si.readObject();
} catch (Exception e) {
System.out.println(e);
}
Use Java Serialization for doing same.
Go with below link for better understand how to convert java object.
Ex. http://www.geeksforgeeks.org/serialization-in-java/
Also You can go with this link:
How to convert the following json string to java object?
Let's say that you have a web page that only contains obfuscated Javascript in the form of an eval(...) function within a script tag.
Dean Edwards' online unpacker (link) correctly unpacks this Javascript.
I would like to write a simple Java class that loads the initial web page (I use HttpClient), extracts the eval(...) function from the HTML, and unpacks it, in order to obtain the de-obfuscated Javascript.
I've tried with Rhino, here's my code :
int start = html.indexOf("<script>eval") + "<script>".length();
int end = html.indexOf("</script>");
javascript = html.substring(start, end);
evaled = eval(javascript);
NativeFunction fEvaled = (NativeFunction) evaled;
String encodedSource = fEvaled.getEncodedSource();
log.info("encodedSource: " + encodedSource);
and the "eval" java function called:
private Object eval(String javascript){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object eval = null;
try {
eval = engine.eval(javascript);
} catch (ScriptException e) {
// TODO Auto-generated catch block
log.error("Exception evaluating javascript " + javascript, e);
}
return eval;
}
But, that doesn't work, the code returned is far from being the correct code (returned by Edwards' unpacker). I've inspected the Rhino variables, found nothing useful.
Am I doing something wrong ?
I'm open to any suggestion, for example if there's a command-line tool that will work I can make a system call.
I'm on Ubuntu.
Thanks.
JsonPath seems to be pretty slow for large JSON files.
In my project, I'd like a user to be able to pass an entire query as a string. I used JsonPath because it lets you do an entire query like $.store.book[3].price all at once by doing JsonPath.read(fileOrString, "$.store.book[3].price", new Filter[0]). Is there a faster method to interact with JSON files in Javascript? It would be ideal to be able to pass the entire query as a string, but I'll write a parser if I have to. Any ideas?
Even small optimizations would be helpful. For instance, I'm currently reading from a JSON file every time I query. Would it be better just to copy the entire file into a string at the beginning and query to the string instead?
EDIT: To those of you saying "this is Javascript, not Java", well, it actually is Java. JsonPath is a Javascript-like query language, but the file I am writing is most assuredly Java. Only the query is written in Javascript. Here's some info about JsonPath, and a snippet of code: https://code.google.com/p/json-path/
List toRet;
String query = "$.store.book[3].price";
try {
// if output is a list, good
toRet = (List) JsonPath.read(filestring_, query, new Filter[0]);
} catch (ClassCastException cce) {
// if output isn't a list, put it in a list
Object outObj = null;
try {
outObj = JsonPath.read(filestring_, query, new Filter[0]);
} catch (Exception e) {
throw new DataSourceException("Invalid file!\n", e, DataSourceException.UNKNOWN);
}
In our web service we set a cookie through JavaScript which we read again in Java (Servlet)
However we need to escape the value of the cookie because it may contain illegal characters such as '&' which messes up the cookie.
Is there a transparent way to escape (JavaScript) and unescape again (Java) for this?
In java you got StringEscapeUtils from Commons Lang to escape/unescape.
In Javascript you escape through encodeURIComponent, but I think the Commons component I gave to you will satisfy your needs.
Client JavaScript/ECMAScript:
encodeURIComponent(cookie_value) // also encodes "+" and ";", see http://xkr.us/articles/javascript/encode-compare/
Server Java:
String cookie_value = java.net.URLDecoder.decode(cookie.getValue());
I'll add further discoveries to my blog entry.
The most accurate way would be to Excecute javascript withing your java code. Hope the code below helps.
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
engine.eval("function decodeStr(encoded){"
+ "var result = unescape(encoded);"
+ "return result;"
+ "};",context);
Invocable inv;
inv = (Invocable) engine;
String res = (String)inv.invokeFunction("decodeStr", new Object[]{cookie.getValue()});
Common lang's StringEscapeUtils didn't work for me.
You can simply use javascript nashorn engine to unescape a escaped javascript string.
private String decodeJavascriptString(final String encodedString) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Invocable invocable = (Invocable) engine;
String decodedString = encodedString;
try {
decodedString = (String) invocable.invokeFunction("unescape", encodedString);
} catch (ScriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return decodedString;
}