As shown in the docs, you should pass your POCO car
directly to Jint.Engine
rather than trying to serialize it to JSON. Jint will use reflection to access its members.
Thus your code can be rewritten as follows:
var value = new Jint.Engine() // Create the Jint engine
.Execute("function car(obj) { const type = obj.Type; return type;}") // Define a function car() that accesses the Type field of the incoming obj and returns it.
.Invoke("car", car); // Invoke the car() function on the car POCO, and return its result.
Or equivalently as:
var value = new Jint.Engine()
.SetValue("obj", car) // Define a "global" variable "obj"
.Execute("const result = (function car(obj) { const type = obj.Type; return type;})(obj)") // Define the car() function, call it with "obj", and set the value in "result"
.GetValue("result"); // Get the evaluated value of "result"
Or
var value = new Jint.Engine() // Create the Jint engine
.SetValue("obj", car) // Define a "global" variable "obj"
.Execute("function car(obj) { const type = obj.Type; return type;}; car(obj);") // Define the car() function, and call it with "obj".
.GetCompletionValue(); // Get the last evaluated statement completion value
Here I am assuming that car
is a POCO that has a string property Type
, e.g.
var car = new
{
Type = "studebaker convertible",
};
Demo fiddle here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…