在C ++代码中将JSON嵌入为字符串

时间:2015-08-18 20:26:22

标签: c++ c-preprocessor

我在Chromium项目中看到了C ++和JSON代码的混合。

例如在此文件中: https://code.google.com/p/chromium/codesearch#chromium/src/gpu/config/software_rendering_list_json.cc

这个宏是神奇吗?

#define LONG_STRING_CONST(...) #__VA_ARGS__

它如何“字符串化”任意JSON内容?

2 个答案:

答案 0 :(得分:5)

Cameron的回答绝对正确。

但是,从C ++ 11开始,有一种编译器支持的方法来创建原始字符串文字。

char const *string = R"someToken({
  "name": "software rendering list",
  "version": "10.9",
  "entries": [
    {
      "id": 1,
      "description": "ATI Radeon X1900 is not compatible with WebGL on the Mac",
      "webkit_bugs": [47028],
      "os": {
        "type": "macosx"
      },
      "vendor_id": "0x1002",
      "device_id": ["0x7249"],
      "features": [
        "webgl",
        "flash_3d",
        "flash_stage3d"
      ]
    },
    {
      "id": 3,
      "description": "GL driver is software rendered. GPU acceleration is disabled",
      "cr_bugs": [59302, 315217],
      "os": {
        "type": "linux"
      },
      "gl_renderer": "(?i).*software.*",
      "features": [
        "all"
      ]
    }
  ]
})someToken";

但请注意,存在一些细微差别。

最明显的是,宏将摆脱C / C ++注释,宏将把所有空格合并到一个空格中。

有关字符串文字的更多详细信息可以在很多地方找到。我喜欢this one

答案 1 :(得分:2)

你猜对了!

宏体内的

#将后续标记转换为包含该标记文本的C字符串文字。在这种情况下,下一个标记是特殊的__VA_ARGS__宏关键字,它被(variadic)宏的所有参数替换,它对应于源代码中的JSON。