【问题标题】:Using a variable in a raw JSON string in C++在 C++ 中使用原始 JSON 字符串中的变量
【发布时间】:2022-08-18 16:57:13
【问题描述】:

我是 C++ 新手,在使用原始 JSON 字符串中的变量时遇到了挑战。

下面的字符串工作正常;

const std::string rawJSON = R\"({\"PID\":14112,\"size\":172,\"daddr\":\"239.255.255.250\",\"saddr\":\"192.168.1.64\",\"dport\":1900,\"sport\":49807})\";

但是我将括号之间的json对象作为变量。在这种情况下如何使用变量? IE

const std::string rawJson = R\"(variable)\";

到目前为止,这是我尝试过的,但出现错误; \"variable\" 包含 json 对象。

            const std::string rawJson = variable;
        const auto rawJsonLength = static_cast<int>(rawJson.length());
        constexpr bool shouldUseOldWay = false;
        JSONCPP_STRING err;
        Json::Value root;

        if (shouldUseOldWay) {
            Json::Reader reader;
            reader.parse(rawJson, root);
        }
        else {
            Json::CharReaderBuilder builder;
            const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
            if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
                &err)) {
                std::cout << \"error\" << std::endl;
                return EXIT_FAILURE;
            }
        }
        const std::string pid = root[\"PID\"].asString();
        const int size = root[\"size\"].asInt();

        std::cout << pid << std::endl;
        std::cout << size << std::endl;
  • 如果您已经将整个 JSON 保存在一个字符串变量中,为什么还需要一个额外的“原始字符串”?看来您可以直接使用variable
  • 你问的是什么叫做字符串插值它被许多语言支持,但不支持 C++。 C++ 中最接近的替代方法是 ostringstream 类。 Boost format 也可能值得一看。

标签: c++


【解决方案1】:

使用简单宏将您的数据类型名称转换为 str。看看这段代码

#include <iostream>
#include <sstream> 
#include <string>
#define JSON_UTILITIES(VAR) #VAR

int main () {
 int key = 0;
 std::stringstream ss;
 ss << JSON_UTILITIES(key) << ":" << key;
 std::cout <<"{ "<< ss.str () << " }"; 
 system ("pause");
 return 0;
}

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 2022-10-15
    • 2021-03-15
    • 2020-05-22
    • 2014-03-03
    • 2011-03-05
    • 1970-01-01
    • 2023-03-18
    • 2021-04-29
    相关资源
    最近更新 更多