pmed / v8pp

Bind C++ functions and classes into V8 JavaScript engine
http://pmed.github.io/v8pp/
Other
901 stars 121 forks source link

JSON.stringify() on exported classes doesn't work #88

Closed VitaminCpp closed 5 years ago

VitaminCpp commented 6 years ago

I've exported a simple class like this...

using ConsoleWrapper = v8pp::class_<Console>;
ConsoleWrapper my_class_wrapper(ctx.isolate());
  my_class_wrapper
  .set("debug", &Console::debug)
  .set("info", &Console::info)
  .set("warn", &Console::warn)
  .set("error", &Console::error)
  .set("log", &Console::log)
  .set("var1", v8pp::property(&Console::getVar1));

...

In Javascript I now want to convert this object to JSON:

var myConsole = new Console();
var str = JSON.stringify(myConsole);
console.log(str);

But this simply outputs an empty object "{}" instead of "{ var1: "dummyString" }". I think this issue has something to do with "enumerable properties"? So what do I have to do to convert an exported C++ object to JSON?

atvise commented 6 years ago

Hi @pmed,

do you know how we can solve this issue ?

Thank you very much!

pmed commented 6 years ago

As I understand, it's possible to set [toJSON()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior) function in a JavaScript class protoptype, and such a function would be invoked on JSON.stringify() call for the corresponding instance.

I've updated v8pp::class_ test to check this behavior.

atvise commented 6 years ago

This looks very promising, thank you! Do you think we could implement this for every exported class automatically ?

atvise commented 6 years ago

I've added a pull request for a generic version #96. Plz have a look :) Thx!

pmed commented 5 years ago

Fixed in #96