菜鸟笔记
提升您的技术认知

RapidJSON解析和生成Json

阅读 : 33

RapidJSON学习

  • RapidJSON获取json数据键值对的key和value
std::string output = "";

output += "Deck: \n";
// deck
for (unsigned j = 0; j < (document["data"])["deck"].Size(); j++) {
  
	// deck内遍历
	for (rapidjson::Value::ConstMemberIterator iter = ((document["data"])[i]["deck"])[j].MemberBegin(); iter != ((document["data"])["deck"])[j].MemberEnd(); iter++) {
  
		rapidjson::Value jKey;
		rapidjson::Value jValue;
		Document::AllocatorType allocator;
		jKey.CopyFrom(iter->name, allocator);
		jValue.CopyFrom(iter->value, allocator);
		if (jKey.IsString()) {
  
			std::string name = jKey.GetString();
			std::string value = cocos2d::Value(jValue.GetInt()).asString();
			output += "    " +  name + ':' + value + '\n';
		}
	}
	output += "    ---\n";
}
output += "---\n";

  • RapidJSON创建Json
    场景:用户输入用户名和密码,然后将信息组合生成json
	rapidjson::Document document;
	document.SetObject();
	rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
	
	//用户名
	rapidjson::Value username(StringRef(usernameInput->getString().c_str()));
	document.AddMember("username", username, allocator);
	
	//密码
	rapidjson::Value password(StringRef(passwordInput->getString().c_str()));
	document.AddMember("password", password, allocator);

	StringBuffer buffer;
	rapidjson::Writer<StringBuffer> writer(buffer);
	document.Accept(writer);
	//log("%s\n", buffer.GetString());