我的代码崩溃(调试错误!R6010 abort()已被调用).你能帮助我吗?我也想知道如何从字符串值初始化json对象.
Json::Value obj;
obj["test"] = 5;
obj["testsd"] = 655;
string c = obj.asString();
Run Code Online (Sandbox Code Playgroud)
Iri*_*nes 29
你好,这很简单:
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;
}
Run Code Online (Sandbox Code Playgroud)
编译:g ++ YourMainFile.cpp -o main -l jsoncpp
我希望它有所帮助;)
Json::Reader如文档中所述,已弃用.以下是如何使用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;
Run Code Online (Sandbox Code Playgroud)
感谢 paolo的答案:用jsoncpp解析JSON字符串
| 归档时间: |
|
| 查看次数: |
36941 次 |
| 最近记录: |