简体   繁体   English

在 C++ 中使用原始 JSON 字符串中的变量

[英]Using a variable in a raw JSON string in C++

I am new to c++ and i have been having a challenge using a variable in a raw JSON string.我是 c++ 的新手,我在使用原始 JSON 字符串中的变量时遇到了挑战。

The string below works fine;下面的字符串工作正常;

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

But i have the json object in between the brackets as a variable.但是我在括号之间有 json object 作为变量。 How can i use the variable in this scenario?在这种情况下如何使用变量? ie IE

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

This is what i have tried so far but i am getting an error;到目前为止,这是我尝试过的,但出现错误; The "variable" holds the json object. “变量”包含 json object。 This a sample code;这是一个示例代码;

#include "json/json.h"
#include <iostream>
#include <memory>

int main() {
const std::string rawJson = R"(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;
return EXIT_SUCCESS;

} }

Use Simple Macro to convert your datatype name to str.have look at this code使用简单宏将您的数据类型名称转换为 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM