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

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

Json::Value obj; obj["test"] = 5; obj["testsd"] = 655; string c = obj.asString(); 
+15
c ++ json jsoncpp
source share
3 answers

Hi, this is pretty simple:

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

2 - Use the Json Reader (Json :: Reader) to read the JSON string and parse the JSON object

3 - Make your stuff :)

Here is a simple code for these 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; } 

Compile: g ++ YourMainFile.cpp -o main -l jsoncpp

I hope this helps;)

+27
source share

Json::Reader deprecated as indicated in the documentation . Here's how to use Json::CharReader and 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; 

Glory to Paolo answer here: Parsing a JSON string with jsoncpp

+5
source share

Please show me the result too.

0
source share

All Articles