Accessing JSON array items from Javascript returned from C# using Jint

295 Views Asked by At

I am trying to communicate back and forth between C# and Javascript, using Jint. Mostly smooth sailing, however I am unable to access items in arrays returned from C# within my JS scripts. Accessing properties on returned objects works fine, but accessing array items always returns null.

Below is my C# code setting up the Jint engine and executing my Javascript.

public class Runtime
{
    public dynamic fetch()
    {
        var json = @"{
            'firstName': 'Anakin',
            'age': 100,
            'kids': ['Luke', 'Leia']
            }";

        var results = JsonConvert.DeserializeObject(json);
        return results;
    }
}

// setup jint engine
var engine = new Engine();
engine.SetValue("runtime", new Runtime());

// execute JS script (see below)
engine.Execute(script);

My Javascript being executed looks like this:

var graph = runtime.fetch();

// accessing simple properties like this works fine
var fname = graph.firstName;
var age = graph.age;

// however, accessing array items returns null
// note: i can get the array, but not the items in the array
var firstKid = graph.kids[0];  //returns null?!

Note: I realize I can return a string from C# and then call JSON.parse(...) from Javascript, but I am trying to avoid the extra step.

Any help is very much appreciated. Thank you.

0

There are 0 best solutions below