deserialize in Node js binary data created in C# - javascript

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);

Related

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

How to send Object in a multipart/form-data request without converting to string in Angular

I have to pass the object in "multipart/form-data" request so that it can be received in downstream application (Java Spring) as List i.e custom class object. Metadata object contains only key and value
In Angular
interface Metadata{
key:string;
value:string;
}
In Angular I am using FormData to create the multipart request as given below.
metadatas = new Array<Metadata>();
// few values added in metadatas array.
fileToUpload: File ; // contains file information
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
formData.append('metadata',JSON.stringify(this.metadatas))
As FormData append method definition says the "value: string | Blob" so I need to convert my metadatas object to string using JSON.stringify().
But when I do so in Spring application (downstream), I can receive the object in String e.g
#PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
#RequestParam(name = "metadata", required = false) String metadata,
#RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
Above code is working and able to get the metadata and file data, but as my API says it should be received in Java Object. So my spring method definition it should be List. Again here the metdata is the object contain key and value.
In Java
public class Metadata {
private String key;
private String value;
// getter and setters
}
In below code the metadata should be capture in List
#PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
#RequestParam(name = "metadata", required = false) List<Metadata> metadata,
#RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
I tried varies things with #RequestPart and #RequestParam, but nothing is working out. As per my understanding, I think that as I am converting the metadata in string while sending from angular hence I am able to received it in String object.
But in FormData I don't have any option to append the object directly as it allows string or Blob. Is there any other way to send the multipart object without converting to string in angular?
Or even if we send the object using FormData how we can received the object in Java Class i.e. List in Spring Boot Application ?
Please help me for getting the solution with the detail explanation as I am new to this.
What is working out for me is:
#PostMapping("/upload_pic")
fun uploadPic(#RequestParam(IMAGE) image: MultipartFile?,
#RequestParam(GROUP_ID) groupId: String,
#RequestHeader(DEVICE_ID_HEADER_STRING) deviceId: String,
#RequestHeader(TOKEN_HEADER_STRING) authToken: String): ResponseEntity<StatusModel> {
All the annotation parameters are String constants.
BTW, this is in kotlin.

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

SHA1 varies in java and javascript for same input

Facing an issue while creating SHA1 from javascript and java. The problem is both are different. It is used for validating the client request to web server. That means client send a based64 encoded security key to server and server regenerate the same key and equate both are same. Please find below code for generating secret keys in client and server.
Server
MessageDigest mDigest = null;
try {
mDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String input = value1 + value1 + server_key;
byte[] result = mDigest.digest(input.getBytes());
String secret = Base64.encodeToString(result, Base64.NO_WRAP);
...
//comparison logic goes here
...
Client (java script)
var input = value1 + value2 + server_key;
//http://code.google.com/p/crypto-js/
var hash = CryptoJS.SHA1(input);
var encoded = base64Encode(hash.toString());
//WEB SERVICE INVOCATION FROM JAVASCRIPT GIES HERE.
The values value1, value1, server_key will be available in both client and server. The issue we are facing is, the SHA1 generated in both client and server is not matching. I understand the issue is in java its using getBytes() and in javascript using string value for generating SHA1. The CryptoJS.SHA1 does not support bytearray as parameter. We cannot change the server code as it is used by many client applications. Any help will be much appreciated.
In Java ->
byte[] result = mDigest.digest(input.getBytes());
and in JavaScript ->
var hash = CryptoJS.SHA1(input);.
I belief this is the problem. In java the parameter is a bytearray and output is also a bytearray. But in javascript the parameter is var (string) and return is also var (string). I 've also compared the output of CryptoJS.SHA1 with some online SHA1 generating tools. The comparison is true. I am not an expert in this area. If you can explain more, it will be more helpful.
I managed it to do in another way. My application is a cordova based application. So generated the sha1 and encoded it from java and objC and invoked it using cordova plugins.

Nashorn/Javascript associative array to Java object?

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;
}

Categories

Resources