Search code examples
javascriptjsondotnetbrowser

DotNetBrowser : passing a json string from .Net to a JavaScript function accepting a json object


I'm trying to transform a json string in .net to that correct type so that I can pass it through the dotnetbrowser bridge to a JavaScript method that is expecting a json object.

My existing code in .net creates a newton-soft json object like so:

JObject obj = new JObject();
obj["src"] = image;
obj["width"] = imageViewModel.Width.Equals(0) ? 64 : imageViewModel.Width;
obj["height"] = imageViewModel.Height.Equals(0) ? 64 : imageViewModel.Height;

I've captured my google map object from the web page:

    public void setGooleMap(JSObject map) {
        CompositionRoot.Invoke(() => {
            googleMap = map;
            foreach (var marker in cachedMarkers) {
                AddMarker(marker);
            }
        });
    }

    private JSObject googleMap;

And now I want to pass an map marker object to a function on the googleMap object:

public void AddMarker(JObject marker) {

//JSObject obj = JSObject.Create(marker.ToString()) as JSObject;
googleMap.GetProperty("addMarker").AsFunction().Invoke(googleMap, marker.ToString());

}

I'd prefer to pass the "obj" like this:

googleMap.GetProperty("addMarker").AsFunction().Invoke(googleMap, obj);

In this code obj is null. How do I get the .net json string transformed to a json object I can pass?


Solution

  • Unfortunately the current version supports auto conversion from .NET object to JS object only for primitive types (numerics, bool and string).

    If you want to pass a non-primitive value, you should create a JSObject or JSONString object from it, for example:

    JSObject obj  = browser.GetJavaScriptContext().CreateObject();
    
    obj.SetProperty("src", image);
    obj.SetProperty("width", imageViewModel.Width.Equals(0) ? 64 : imageViewModel.Width);
    obj.SetProperty("height", imageViewModel.Height.Equals(0) ? 64 : imageViewModel.Height);