C++ Json-cpp - 如何从字符串初始化并获取字符串值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31121378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:51:39  来源:igfitidea点击:

Json-cpp - how to initialize from string and get string value?

c++jsonjsoncpp

提问by Greyshack

My code below crashes(Debug Error! R6010 abort() has been called). Can you help me? I'd also would like to know how to initialize the json object from a string value.

我下面的代码崩溃了(调试错误!R6010 abort() 已被调用)。你能帮助我吗?我还想知道如何从字符串值初始化 json 对象。

Json::Value obj;
obj["test"] = 5;
obj["testsd"] = 655;
string c = obj.asString();

回答by Irineu Antunes

Hello it is pretty simple:

你好,很简单:

1 - You need a CPP JSON value object (Json::Value) to store your data

1 - 您需要一个 CPP JSON 值对象 (Json::Value) 来存储您的数据

2 - Use a Json Reader (Json::Reader) to read a JSON String and parse into a JSON Object

2 - 使用 Json Reader (Json::Reader) 读取 JSON 字符串并解析为 JSON 对象

3 - Do your Stuff :)

3 - 做你的事:)

Here is a simple code to make those steps:

这是一个简单的代码来完成这些步骤:

#include <stdio.h>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>
#include <jsoncpp/json/value.h>
#include <string>

int main( int argc, const char* argv[] )
{

    std::string strJson = "{\"mykey\" : \"myvalue\"}"; // need escape the quotes

    Json::Value root;   
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( strJson.c_str(), root );     //parse process
    if ( !parsingSuccessful )
    {
        std::cout  << "Failed to parse"
               << reader.getFormattedErrorMessages();
        return 0;
    }
    std::cout << root.get("mykey", "A Default Value if not exists" ).asString() << std::endl;
    return 0;
}

To compile: g++ YourMainFile.cpp -o main -l jsoncpp

编译: g++ YourMainFile.cpp -o main -l jsoncpp

I hope it helps ;)

我希望它有帮助;)

回答by mts knn

Json::Readeris deprecated, as stated in the documentation. Here's how to use Json::CharReaderand Json::CharReaderBuilder:

Json::Reader已弃用,如文档中所述。以下是如何使用Json::CharReaderJson::CharReaderBuilder

std::string strJson = R"({"foo": "bar"})";

Json::CharReaderBuilder builder;
Json::CharReader* reader = builder.newCharReader();

Json::Value json;
std::string errors;

bool parsingSuccessful = reader->parse(
    strJson.c_str(),
    strJson.c_str() + strJson.size(),
    &json,
    &errors
);
delete reader;

if (!parsingSuccessful) {
    std::cout << "Failed to parse the JSON, errors:" << std::endl;
    std::cout << errors << std::endl;
    return;
}

std::cout << json.get("foo", "default value").asString() << std::endl;

Kudos to p-a-o-l-o for their answer here: Parsing JSON string with jsoncpp

感谢 paolo 的回答:Parsing JSON string with jsoncpp