方式一:
/**
* @brief 构造http结果字符串.
*/
void GenHttpResponse(const int code, const char* msg, const char* token, rapidjson::Document& doc)
{
doc.SetObject();
rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();\
//result字段;
if (token && strlen(token) > 0)
{
rapidjson::Value res_obj(rapidjson::Type::kObjectType);
rapidjson::Value token_val(rapidjson::Type::kStringType);
token_val.SetString(rapidjson::StringRef(token), allocator);
res_obj.AddMember(rapidjson::StringRef(string_define::TOKEN.c_str()), token_val, allocator);
doc.AddMember(rapidjson::StringRef(string_define::RESULT.c_str()), res_obj, allocator);
}
//error字段;
rapidjson::Value err_obj(rapidjson::kObjectType);
rapidjson::Value code_val(rapidjson::kNumberType);
err_obj.AddMember(rapidjson::StringRef(string_define::CODE.c_str()), code_val, allocator);
rapidjson::Value msg_val(rapidjson::Type::kStringType);
msg_val.SetString(rapidjson::StringRef(msg ? msg : kEmptyStr.c_str()), allocator);
err_obj.AddMember(rapidjson::StringRef(string_define::MESSAGE.c_str()), msg_val, allocator);
doc.AddMember(rapidjson::StringRef(string_define::ERROR.c_str()), err_obj, allocator);
}
方式二:
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject(); // Between StartObject()/EndObject(),
writer.Key("hello"); // output a key,
writer.String("world"); // follow by a value.
writer.Key("t");
writer.Bool(true);
writer.Key("f");
writer.Bool(false);
writer.Key("n");
writer.Null();
writer.Key("i");
writer.Uint(123);
writer.Key("pi");
writer.Double(3.1416);
writer.Key("a");
writer.StartArray(); // Between StartArray()/EndArray(),
for (unsigned i = 0; i < 4; i++)
writer.Uint(i); // all values are elements of the array.
writer.EndArray();
writer.EndObject();
// {"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}
std::cout << s.GetString() << std::endl;