欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ rapidjson使用

程序员文章站 2024-02-04 08:27:04
...
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace std;

#define CONFIG_JSON "{\"Para\":{\"key\":\"value\",\"key2\":\"key2\"},\"db\":{\"server\":\"127.0.0.1\"},\"ACCESS\": {\"startip\":\"192.168.14.1\",\"endip\":\"192.168.14.254\"},\"ras\":{\"xxx\":\"eee\"}}"

#define AUTH_JSON "{\"root\":{\"user\":\"xxxx\",\"pass\":\"cccc\"}}"

#define CMD_JSON "{\"cmd\":\"GetAuthStatus\",\"starttime\":\"xxxxx\",\"endtime\":\"yyyyyy\"}"

#define SYNC_JSON "{\"Para\":{\"GroupAttr\":\"test1\",\"RatesGroup\":\"2\",\"PackageGroup\":\"3\"}}"

void testcmd(char* szcmd)
{
	rapidjson::Document doc;
	if (doc.Parse<0>(szcmd).HasParseError())
	{
		cout << "---------------------json is faild" << endl;
		return;
	}
	rapidjson::Value& valArray = doc;
	if (!valArray.HasMember("cmd") || !valArray.HasMember("starttime"))
	{
		cout << "json param faild" << endl;
		return;
	}
	cout << valArray["cmd"].GetString() << endl;
	cout << valArray["starttime"].GetString() << endl;
}

void testconf(char* szconf)
{
	rapidjson::Document doc;
	if (doc.Parse<0>(szconf).HasParseError())
	{
		cout << "---------------------json is faild---" << doc.GetParseError() << endl;
		return;
	}
	const rapidjson::Value& membersArray = doc["db"];
	for (rapidjson::Value::ConstMemberIterator it = membersArray.MemberBegin(); it != membersArray.MemberEnd(); it++)
	{
		cout << it->name.GetString() << endl;
		cout << it->value.GetString() << endl;
		//cout<<it->FindMember("GroupAttr")->value.GetString()<<endl;
			 //cout<<it["GroupAttr"].GetString()<<endl;
	}
	//if(!valArray.HasMember("server") || !valArray.HasMember("server"))
	//{
	//    cout<<"json param faild"<<endl;
	//  return;
	//}
	//cout<<valArray["server"].GetString()<<endl;
	//cout<<valArray["startip"].GetString()<<endl;
}

void testsync(char* szconf)
{
	rapidjson::Document doc;
	if (doc.Parse<0>(szconf).HasParseError())
	{
		cout << "---------------------json is faild" << endl;
		return;
	}
	rapidjson::Value& valArray = doc["Para"];
	if (!valArray.HasMember("GroupAttr") || !valArray.HasMember("RatesGroup") || !valArray.HasMember("PackageGroup"))
	{
		cout << "json param faild" << endl;
		return;
	}
	cout << valArray["GroupAttr"].GetString() << endl;
	cout << valArray["RatesGroup"].GetString() << endl;
	cout << valArray["PackageGroup"].GetString() << endl;
}


int main()
{

	//testcmd(CMD_JSON);
	testconf(CONFIG_JSON);
	//testsync(SYNC_JSON);
	return 0;
}