how to return js object to unity - javascript

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

Related

How to properly parse C# List of objects to Javascript. Only shows type like " System.Collections.Generic.List`1"

I really cant wrap my head around this i have a List of this class
public class StandardText
{
public string Id { get; set; }
public string Value { get; set; }
}
I then want to use it in javascript where i pass down a model to a partialView. The problem is that i dont seem to be able to use it. i tried to JSON.parse() the list in the javascript but it will then try to JSON.parse() something like " System.Collections.Generic.List`1" so it is not trying to actually parse the values of the object. i also tried to JsonConvert before i send it down but i am failing on how to porperly convert it.
this is where i create the model and then send down the partialView
public async Task<ActionResult> _confirmText(TextViewModel model)
{
model.StandardText = await GetStandardText();
return PartialView(model);
}
Then in that partialView i simply want to pass it to my frontend via a global scope(i know bad)
var text = '#Model.StandardText';
window.addElementToModal(element, text);
And then the addElementToModal
(window as any).addElementToModel = ((root: HTMLElement, standardText: {[key: string]: string}) =>
{
init(root, standardText);
});
so i want to recieve it like {[key: string]: string} where am i going wrong?
Try this code:
const list = JSON.parse("#JsonConvert.SerializeObject(ViewBag.List)");
As a result you will get a plain JS array in list variable.
var text = '#Model.StandardText';
This is just going to ToString() the object. You could use JSON.NET For example to JSON Stringify it if that's your objective. e.g.
var text = '#Json.SerializeObject(Model.StandardText)';

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

Add unparsable cruft to ASP.NET MVC JsonResult

In light of posts such as these:
JSON unparseable cruft: Why so serious?
Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses?
Why does Google prepend while(1); to their JSON responses?
I would like to follow the advice laid out in the following answer: How should web app developers defend against JSON hijacking?
Is there an easy way to add an unparsable cruft to JSON responses built using System.Web.Mvc.JsonResult? The security.se post suggests that I use </* at the beginning of the response.
You could write a custom action result to perform this:
public class SafeJsonResult: JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("</*");
base.ExecuteResult(context);
}
}
and then use it instead of the default one:
public ActionResult Index()
{
return new SafeJsonResult
{
Data = new { Foo = "bar" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
};
}

Error using dynamic keyword in asp.net mvc 4

I am getting this long error when i accpet the parameter as dynamic on my server side action method in mvc 4.
{"Message":"An error has
occurred.","ExceptionMessage":"'Newtonsoft.Json.Linq.JObject' does not
contain a definition for
'TournamentId'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":"
at CallSite.Target(Closure , CallSite , Object )\r\n at
System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite
site, T0 arg0)\r\n at
ManagerDeTorneos.Web.Controllers.TournamentDateController.Create(Object
data) in
F:\Prince\Projects\Juan\trunk\ManagerDeTorneos.Web\Controllers\TournamentDateController.cs:line
133\r\n at lambda_method(Closure , Object , Object[] )\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c_DisplayClass13.b_c(Object
instance, Object[] methodParameters)\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object
instance, Object[] arguments)\r\n at
System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1
func, CancellationToken cancellationToken)"}
[HttpPost]
public HttpResponseMessage AddMatch(dynamic data)
{
int tournamentDateId = (int)data.TournamentDateId.Value;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
In The above method data Contains tournamentId as sent from ajax call as JSON.Stringify({'TournamentId':'5'}).
Can anybody tell me what is the cause of error. I even replaced the dll of Newtonsoft.Json as well
You are right dan but i fixed my issue by removing that dll from GAC. May be in GAC it was using old assembly
The error is caused by the fact that you typed your parameter as dynamic, which means that the model binder doesn't know what to make it. It's the same as if you were to declare it as an object. Since you are providing JSON, it serializes the object as a Json.Net JObject. Just because you define it as a dynamic doesn't mean that it's going to magically take whatever shape you need it to.
Change it to a concrete type - something that matches the structure of the provided JSON:
public class TournamentInfo
{
public int TournamentId { get; set; }
}
[HttpPost]
public HttpResponseMessage AddMatch(TournamentInfo data)
{
int tournamentDateId = data.TournamentId;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
This way, the binder knows what it's supposed to turn the JSON into, and since TournamentInfo matches the structure of the JSON, it won't have any trouble serializing it.
Don't misuse dynamic. It was not introduced into C# so developers could stop defining classes.

JSON representation of a list of keyvaluepairs

I have an MVC JSON controller method that I call from frontend. It looks like this:
public JsonResult FacetedSearch(string searchString, List<KeyValuePair<string,string>> facets)
I'm calling it via jQuery ajax at the frontend, I'm serializing the data in the following manner:
JSON.stringify({searchString: "the matrix", facets: [{Key: "TypeName", Value: "Feature Film"}, {Key:"TypeName", Value:"Series"}]}
When I debug through my application code, I see that searchString gets passed successfully over to the MVC method, but the variable facets gives me a list of 2 KeyValuePairs with null Key and Value.
I've looked at my serialization and it seems valid but for whatever reason it isn't going over to my application correctly. What gives?
Rather than expect two objects in your signature, it would make more sense to expect a single object that contains both of your parameters. This would be something like the following.
public JsonResult FacetedSearch(RequestObject requestObject)
{ }
public class RequestObject
{
public string searchString { get; set; }
public List<KeyValuePair<string,string>> facets { get; set; }
}
This way, when you send your JSON object, the signature is an object with two properties, just like the object that you are sending.
Per Is there a serializable generic Key/Value pair class in .NET?
I found out why it's not serializing it. Apparently it's unserializable.

Categories

Resources