簡體   English   中英

Json-cpp - 如何從字符串初始化並獲取字符串值?

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

我下面的代碼崩潰了(調試錯誤。R6010 abort() 已被調用)? 你能幫助我嗎。 我還想知道如何從字符串值初始化 json object。

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

你好,很簡單:

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

我希望它有幫助;)

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;

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

您可以通過使用 stringstream 來避免使用 Json::CharReader 和 Json::CharReaderBuilder。

#include <string>
#include <sstream>
#include "jsoncpp/json/json.h"
    
int main() {
        std::string strJson = "{\"mykey\" : \"myvalue\"}"; 
        Json::Value obj;
    
        // read a JSON String
        stringstream(strJson) >> obj;
    
        // get string value
        std::string value1 = obj["mykey"].asString();

        // or to get a default value if it isn't set
        std::string value2 = obj.get("mykey", "...").asString();
        return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM