rapidjson parses json code instances
Look directly at the code:
#include <iostream>
#include <stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<sstream>
// Please download the open source one yourself rapidjson
#include "rapidjson/prettywriter.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/memorystream.h"
using namespace std;
using rapidjson::Document;
using rapidjson::StringBuffer;
using rapidjson::Writer;
using namespace rapidjson;
string getStringFromJson(const string &jsStr, const string &strKey)
{
Document document;
if (document.Parse(jsStr.c_str()).HasParseError() || !document.HasMember(strKey.c_str()))
{
return "";
}
const rapidjson::Value &jv = document[strKey.c_str()];
return jv.GetString();
}
int main(int argc, char *argv[])
{
string s = "{\"code\":0,\"msg\":\"ok\"}";
cout << s << endl;
cout << getStringFromJson(s, "msg") << endl;
return 0;
}
Results:
[
{“code”:0,“msg”:“ok”} ok
]
Note:
1. If not document.Parse(jsStr.c_str()).HasParseError() core dump
2. If not !document.HasMember(strKey.c_str()) core dump
3. code is 0 and is an integer. If the above getStringFromJson is called, core dump will be used return jv.GetInt();
Life is short. I love rapidjson
conclusion