#include "JSValueHelper.h" #include #include std::string ToString(v8::Local object) { v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); v8::Local context = isolate->GetEnteredOrMicrotaskContext(); if (object->IsString() || object->IsRegExp() || object->IsFunction()) { v8::String::Utf8Value utf8(isolate, object); return std::string(*utf8); } if (object->IsObject()) { v8::MaybeLocal str = v8::JSON::Stringify( context, object->ToObject(context).ToLocalChecked()); if (str.IsEmpty()) { return ""; } v8::Local s = str.ToLocalChecked(); v8::String::Utf8Value str2(isolate, s); return std::string(*str2 ? *str2 : ""); } v8::Local global = context->Global(); v8::Local JSON = global->Get(context, NewV8String("JSON")) .ToLocalChecked() ->ToObject(context) .ToLocalChecked(); v8::Local argv[] = {object}; v8::Local JSON_stringify = v8::Local::Cast( JSON->Get(context, NewV8String("stringify")).ToLocalChecked()); v8::String::Utf8Value str( isolate, JSON_stringify->Call(context, JSON, 1, argv).ToLocalChecked()); return std::string(*str ? *str : ""); } v8::Local ObjectToJS(QObject *object) { QJsonObject jsonObject; QList propertyNames = object->dynamicPropertyNames(); foreach (QByteArray propertyName, propertyNames) { QString key = QString::fromStdString(propertyName.toStdString()); object->property(propertyName).toString(); if (key == "undefined" || key.isEmpty()) { } else { jsonObject[key] = QJsonValue::fromVariant(object->property(propertyName)); } } QJsonDocument doc(jsonObject); QString strJson(doc.toJson(QJsonDocument::Compact)); v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handleScope(isolate); v8::Local context = isolate->GetEnteredOrMicrotaskContext(); v8::Local jsString = NewV8String(strJson.toUtf8().constData()); v8::Local ret = v8::JSON::Parse(context, jsString).ToLocalChecked(); return handleScope.Escape(ret); }