Nashorn/Javascript associative array to Java object? - javascript

I'm trying to integrate the JavaScript in my Wicket project into my TestNG test suite. I decided to give project Nashorn a try.
Now I want to parse results from nashorn. I return an associative array from javascript, and get a ScriptObjectMirror as returned type.
ScriptEngine engine = factory.getEngineByName( "nashorn" );
String content = new String( Files.readAllBytes( Paths.get( "my-funcs.js" ) ) );
Object result = engine.eval( content + ";" + script );
Of course, I can JSON.stringify the array, using more javascript script, and parse it back using Gson or similar libraries, but is there a more native approach to this mapping problem?

Thanks to the above comments, I found a relatively nice solution, using Apache Commons BeanUtils
public static class MyResult
{
private String prop1;
public void setProp1(String s)
{
...
}
}
...
public MyResult getResult(String script)
{
//ugly-but-fast-to-code unchecked cast
ScriptObjectMirror som = (ScriptObjectMirror) engine.eval(script);
MyResult myResult = new MyResult();
BeanUtils.populate(myResult, som);
return myResult;
}

Related

deserialize in Node js binary data created in C#

i have a byte array created in c# from object type and then send it over socket protocol to a Node js app, but unable to deserialize the data to readable object. what is the way to decode this data?
C# serializing code:
private static byte[] ToBytes(object message)
{
IFormatter br = new BinaryFormatter();
byte[] keyAsBytes = null;
using (var ms = new MemoryStream())
{
br.Serialize(ms, message);
keyAsBytes = ms.ToArray();
}
return keyAsBytes;
}
object o = 801507;
byte[] AsBytes = ToBytes(o);
// send AsBytes
And in node js i try to decode the data
function handleMessage(message) {
console.log(message.toString());
}
And the above code print me {"type":"Buffer","data":[0,1,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,4,1,0,0,0,12,83,121,115,116,101,109,46,73,110,116,54,52,1,0,0,0,7,109,95,118,97,108,117,101,0,9,227,58,12,0,0,0,0,0,11]}
so what is the right way to get the origin value ?
You are sending array of bytes (creted from c# object) to Node js. You probablly want send something more useful preferebly a string. To create (serialize) string (json object) from c# object use serializer / converter. In newer version of .net you have built in var jsonString = System.Text.Json.JsonSerializer.Serialize(object) or you can use Newtonsoft.Json nuget package to achieved the same thing. Newtonsoft.Json variant var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(object);

how to return js object to unity

I'm using the Google Draco decoder to decode mesh the following.
var dracoGeometry;
dracoGeometry = new decoderModule.Mesh();
decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
when I check the type of the draceGeometrytry:
console.log( typeof dracoGeometry);
I get the
"object" type.
Now my problem is "how can I return this object to unity". What return type supported in C# to accept js object?
You can send strings or numbers, so what I would do is create a js object that has the data you need then call JSON.stringify on it to convert it to a string then send that over using unityInstance.SendMessage:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
// in a script attached to a gameobject named "MyGameObject"
void MyMethod(string s)
{
Debug.Log(s);
// decode from json, do stuff with result etc
}
As for what you can do with that data while it is in JSON string form, you can use a variety of solutions to decode the JSON string once you have it in Unity. See Serialize and Deserialize Json and Json Array in Unity for more information.
So if your js looks like this:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
sendToUnity({
playerId: "8484239823",
playerLoc: "Powai",
playerNick:"Random Nick"
});
You could do something like this in Unity:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
...
void MyMethod(string s)
{
Player player = JsonUtility.FromJson<Player>(s);
Debug.Log(player.playerLoc);
}
Source: Programmer's answer
There are some methods available, but it doesn't seem possible at the moment to send a mesh from js to unity. If you are working with google draco, I recommend you to follow this fork

Retrieve javascript object in java with rhino

I want to get a javascript object from a javascript file, that only constists of this one big object.
For example:
var cars = {
mercedes: {
colour: 'silver',
drivemode: 'alldrive'
},
audi: {
size: '4x2x1,5m'
speed: '220 kmph'
}
};
For the javapart I am using rhino to get that object. For now I have coded:
Context context = context.enter();
context.setOptimizationLevel(9);
context.setLangaugeVersion(170);
context.getWrapFactory().setJavaPrimitiveWrap(false);
Scriptable defaultScope = context.initSafeStandardObjects();
So now i should have the possibility to be able to retrieve the javascript object. But how?
Script function = context.compileString("Any javascriptfunction as String", "javaScriptFile.js", 1, null);
function.exec(context, defaultScope);
But what would that javascript function look like to get that object as JSON (something like cars.stringify() )? And further more is that the right approach in using this function?
And finally how and where to i save the object in a java Object?
i have already checked this post and this post also this post but all dont fit my criteria or are missing out on a code example for clarification
Edit:
I have found another approach in calling/writing a javascript function in java as a string like:
Scriptable scriptObject;
private String functionAsString = "function getAsJson() {var objectString = { colour: \"silver\", drivemode: \"alldrive\" };return JSON.stringify(objectString);}";
Function fct = context.compileFunction(defaultScope, functionAsString, "AnyName", 1, null);
Object result = fct.call(context, defaultScope, scriptObject, null);
The only problem still standing is how do it get "objectString" to contain my cars.js? There somehow has to be a possibility to load that object in this variable
probably something like:
String functionAsString2 = "get cars() {return this.cars;}";
But how/and where do i specify the file in which to use this function?
I have found a way to retrieve the object by using the ScriptEngine from Rhino
private ScriptEngineManager manager = new ScriptEngineManager();
private ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval(Files.newBufferReader("PATH TO THE JAVASCRIPT FILE", StandardCharsets.UTF_8));
Object result = engine.get("cars"); //Variable in the javascript File
if(result instanceof Map){
result = (Map<String,Object>) result;
}
so the object is retrieved and can be accessed and casted as a Map> and recursively accesed to in the end having a java Object of the JavaScript Object.
No need to use functions

Unit Testing How can I deserialize a JSON object into dynamic object using json-net

Using MSTest, when I try to run a test that has a type of dynamic that is a container of a JSON object (from an API Query) I am ment to be able to dereference the JSON elements in the commented out be below, but it fails, where as treating it as an item collection it seems ok.
If inspect '(jsonResponse.message)' it has a value of "Hi" - but it wont work in a Unit Test.
Why is that?
// http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm
// Deserialize json object into dynamic object using Json.net
[TestMethod]
public void DynamicDeserialization()
{
dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
JObject d = JObject.Parse("{\"message\":\"Hi\"}");
Assert.IsTrue((string)d["message"] == "Hi"); // Is ok
// Assert.IsTrue(jsonResponse.message.ToString() == "Hi"); // is not ok
}
Uncommented last line, ran the code and test worked/passed. If you look at jsonResponse while debugging you will see that it is a JObject as well wrapped as dynamic.
In fact if I convert d to dynamic I can perform the same assertion and it passes as well.
[TestMethod]
public void DynamicDeserialization() {
var json = "{\"message\":\"Hi\"}";
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
dynamic d = JObject.Parse(json);
Assert.IsTrue(d.message.ToString() == "Hi");
Assert.IsTrue(jsonResponse.message.ToString() == "Hi");
}
You may need to check to make sure you are using the latest version of Json.Net

.net 2.0: getting all keys and values pairs from object, passed from JS

I have a C# application in web page. Web calls my apllication via JS:
var data = {key1:value1, key2:value2};
app["methodName"](data);
So, in my app:
public void methodName(dynamic data)
{
foreach (KeyValuePair pair in data)
{
Debug.Log(pair.Name + ": " + pair.Value)
}
}
But the problem is, I'm forced to use .net v2.0, and dynamic is not available.
Is there any way to avoid it?
if you want the keys and values in javascript try this
Object.keys(data) ///will return the array of keys
Refer : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
hope this helps

Categories

Resources