RapidJson use

rapidJson use

Write Json: Create a simple json structure

Method 1: Use rapidjson
	#define JSON_KEY_NAME_CONTENT "body"
	#define JSON_KEY_NAME_DATATYPE "type"
	#define JSON_KEY_REPORT_NAME_ACTIONRESULT "ActionRes"
	#define JSON_DATA_TYPE_WEAK_PASSWORD_OPTION_CHANGE "reportWeakPasswordOptionChange"

	rapidjson::StringBuffer reportBuff;
	rapidjson::Writer<rapidjson::StringBuffer> reportwriter(reportBuff);
	reportwriter.StartObject();
	reportwriter.Key(JSON_KEY_NAME_CONTENT);
	reportwriter.StartArray();
	reportwriter.StartObject();
	reportwriter.Key(JSON_KEY_REPORT_NAME_ACTIONRESULT);
	reportwriter.Int(ret);
	reportwriter.EndObject();
	reportwriter.EndArray();
	reportwriter.Key(JSON_KEY_NAME_DATATYPE);
	reportwriter.String(JSON_DATA_TYPE_WEAK_PASSWORD_OPTION_CHANGE);
	reportwriter.EndObject();
	std::string jsonstring = reportBuff.GetString()//改部分是将json转换为char *;

Last build
An object
a jsonobject there are two objects, body array, type to string.
Note StartObject and EndObject, and StartArray and EndArray need in pairs.

Second way: Using AddMember add elements
		rapidjson::Document jsonDoc;    //生成一个dom元素Document
		rapidjson::Document::AllocatorType &allocator = jsonDoc.GetAllocator(); //获取分配器
		jsonDoc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
		jsonDoc.AddMember("ReplyTo", rapidjson::StringRef("test string"), allocator);
		jsonDoc.AddMember("Body", rapidjson::StringRef(""), allocator);
		int s = 10;
		jsonDoc.AddMember("Score",s,allocator);
		rapidjson::StringBuffer strBuf;
		rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
		jsonDoc.Accept(writer);
		std::string data = std::string(strBuf.GetString());

This is an example copied from somewhere else over, to add an array

	rapidjson::Value object(rapidjson::kObjectType); // 创建对象
	bject.AddMember("int", 1, allocator);         // 添加 "int" : 1
    object.AddMember("double", 1.1, allocator);    // 添加 "double" : 1.1
    object.AddMember("hello", "world", allocator); // 添加 "hello" : "world"
    
    //[4.2] 往json数组中添加数据:值
    rapidjson::Value array(rapidjson::kArrayType); // 创建数组
    rapidjson::Value str(rapidjson::kStringType);  // 字符串
    rapidjson::Value obj(rapidjson::kObjectType);  // 对象
    str.SetString("hello"); // 设置str的值
    obj.AddMember("name", "alice", allocator);
    obj.AddMember("age", 23, allocator);

    array.PushBack(123, allocator);   // 添加数字
    array.PushBack("888", allocator); // 添加字符串,方式一
    array.PushBack(str, allocator);   // 添加字符串,方式二
    array.PushBack(obj, allocator);   // 添加对象
    //[4.3] 往对象格式的json文件中添加数据
    d.AddMember("hello", "world", allocator);
    d.AddMember("object", object, allocator);
    d.AddMember("array", array, allocator);

Here Insert Picture Description

Read Json

Reference article:
1, Json data manipulation

Released two original articles · won praise 0 · Views 50

Guess you like

Origin blog.csdn.net/sinat_38602176/article/details/104040421
use
use