CLR class with toJSON method throws a "JavaScriptException: No public methods with the specified arguments were found" error on JSON.stringify #2290
Answered
by
kxs-rgamezdiaz
kxs-rgamezdiaz
asked this question in
Q&A
-
|
I am using Jint 4.6.0.0 and need to add a toJSON method explicitly, which causes a "No public methods with the specified arguments were found" error. Example: public sealed class MyClassToJson()
{
public string toJSON() => "{ \"name\": \"MyClassToJson\" }";
}
[TestMethod]
public void TestToJson() // Passes
{
Jint.Engine engine = new();
MyClassToJson myClass = new();
engine.SetValue("myClass", myClass);
string result = engine.Evaluate("myClass.toJSON()").ToString();
Assert.AreEqual(myClass.toJSON(), result);
}
[TestMethod]
public void TestJsonStringify() // Fails
{
Jint.Engine engine = new();
MyClassToJson myClass = new();
engine.SetValue("myClass", myClass);
string result = engine.Evaluate("JSON.stringify(myClass)").ToString();
Assert.AreEqual(myClass.toJSON(), result);
}The Is this a bug or limitation in Jint? Is there a workaround? I need to have a toJSON method on my js class. Thank you for your help. |
Beta Was this translation helpful? Give feedback.
Answered by
kxs-rgamezdiaz
Feb 16, 2026
Replies: 1 comment
-
|
Looks like I found a workaround, we need to return an public sealed class PersonWithToJsonJsValue(Jint.Engine engine)
{
public string name { get; set; }
public int age { get; set; }
public ObjectInstance toJSON(JsValue v)
{
ObjectInstance obj = engine.Intrinsics.Object.Construct([]);
obj.Set("name", name);
obj.Set("age", age);
return obj;
}
}
[TestMethod]
public void TestJsonStringifyWithObjectWithToJsonReturningJsValue()
{
Jint.Engine engine = new();
PersonWithToJsonJsValue person = new(engine) { name = "John", age = 30 };
engine.SetValue("person", person);
string result = engine.Evaluate("JSON.stringify(person)").ToString();
Assert.AreEqual("{\"name\":\"John\",\"age\":30}", result);
}I will mark this an answer and change it later someone finds out how to do better. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
kxs-rgamezdiaz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like I found a workaround, we need to return an
ObjectInstancefor thetoJSONmethod.