Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

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

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.

Json::Value obj;
obj["test"] = 5;
obj["testsd"] = 655;
string c = obj.asString();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hello it is pretty simple:

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

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

3 - Do your Stuff :)

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

I hope it helps ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...