CEF生成JSON数据

在“使用CEF的JSON解析功能”中介绍了使用CefParseJson方法,与之相应的另一个CefWriteJson方法,能够用来生成JSON串(或二进制),其函数原型例如以下:

// Generates a JSON string from the specified root |node| which should be a
// dictionary or list value. Returns an empty string on failure. This method
// requires exclusive access to |node| including any underlying data.
/*--cef()--*/
CefString CefWriteJSON(CefRefPtr<CefValue> node,
                       cef_json_writer_options_t options);

注意第一个參数是CefValue类型,在cef_values.h中定义,是CEF里的通用类型。

当我们要调用CefWriteJSON时必须传入此类型的数据,假如你的JSON数据通过CefListValue或CefDictionaryValue来表示,就须要将它们设置到一个CefValue实例中再传递给CefWriteJSON。

以下是使用CefWriteJSON的一个简单演示样例:

void testWriteJson()
{
    CefRefPtr<CefDictionaryValue> pDict = CefDictionaryValue::Create();
    pDict->SetInt("id", 123);
    pDict->SetString("name", "ZhangSanFeng");

    CefRefPtr<CefValue> pValue = CefValue::Create();
    pValue->SetDictionary(pDict);
    std::string jsonString = CefWriteJSON(pValue, JSON_WRITER_DEFAULT);

    OutputDebugStringA(jsonString.c_str());
}

相应生成的JSON串例如以下:

{
    "id":123,
    "name":"ZhangSanFeng"
}

JSON数据可能是我们基于CEF开发富client程序时,在JS和C++之间通信最方便的格式了。以上面的数据为例,传递到JS上下文中,就能够用obj.id、obj.name之类的形式来訪问。


就这样吧。

其它參考文章详见我的专栏:【CEF与PPAPI开发】。

原文地址:https://www.cnblogs.com/cynchanpin/p/7240423.html