【问题标题】:Json-cpp - how to initialize from string and get string value?Json-cpp - 如何从字符串初始化并获取字符串值?
【发布时间】:2015-09-16 06:03:56
【问题描述】:

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

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

【问题讨论】:

    标签: c++ json jsoncpp


    【解决方案1】:

    你好,很简单:

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

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

    3 - 做你的事:)

    以下是完成这些步骤的简单代码:

    #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;
    }
    

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

    希望对你有帮助;)

    【讨论】:

    • 哇,这是我见过的关于 C++ 和 json 的最好的快速入门。真棒
    • 谢谢,喜欢节省时间。
    • 对于原始字符串 (C++11),您可以使用 strJson = R"({"mykey" : "myvalue"})";。
    • FWIW,您应该只需要包含单个 json.h 标头。
    • Json::Reader 已弃用。请改用 CharReader 和 CharReaderBuilder。
    【解决方案2】:

    Json::Reader is deprecated. 改用Json::CharReader 和Json::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;
    

    感谢 p-a-o-l-o 在这里的回答:Parsing JSON string with jsoncpp

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2013-05-20
    • 2022-11-17
    • 2018-07-31
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多