C++项目RapidJson用法总结

1.构造复杂Json,例子详解:

//整个Json字符串由一个Document对象来管理

rapidjson::Document document;
document.SetObject();

//添加name:value对

const char *name = "name";
const char *value = "zhangdada";
document.AddMember(rapidjson::StringRef(name), rapidjson::StringRef(value), document.GetAllocator());


//添加Json 对象

rapidjson::Value info_objects(rapidjson::kObjectType);
std::string jsonObject = "json_object";
info_objects.AddMember(rapidjson::StringRef("class_room"), rapidjson::StringRef("NO.6110"), document.GetAllocator());
info_objects.AddMember(rapidjson::StringRef("teacher_name"), rapidjson::StringRef("ZhangSanfeng"), document.GetAllocator());
document.AddMember(rapidjson::StringRef(jsonObject.c_str()), info_objects, document.GetAllocator());

//添加Json 数组
rapidjson::Value array_objects(rapidjson::kArrayType);
for (int i = 0; i < 2; i++)
{
    Value object(kObjectType);
    Value nobject(kNumberType);
    nobject.SetInt(i);
    object.AddMember(StringRef("id"), nobject, document.GetAllocator());
    object.AddMember(StringRef("name"), StringRef("zhangsan"), document.GetAllocator());
    array_objects.PushBack(object, document.GetAllocator());
}
char *jsonarrayname = "jsonarrayname";
document.AddMemory(rapidjson::StringRef(jsonarrayname), array_objects, document.GetAllocator());

//将构造好的json转化成c++字符串的形式
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string json = std::string(buffer.GetString));

2.构造简单json对象:

  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;

3.json对象解析:

const char *buffer = "{"code":200, "data":{"name":"jianli", "age":25}}";

Document document;
document.Parse<rapidjson::kParseDefaultFlags>(buffer);

if(document.HasParseError())
{
    printf("%s\n", "Json object parse failed.");
}

if(!document.HasMember("code"))
{
    printf("%s\n", "Json object has no \"code\" member.");
}
rapidjson::Value &obj1 = document["code"];


rapidjson::Value &obj2 = document["data"];
if(!obj2.IsObject())
{
    printf("%s\n", "obj2 is not a object.");
}

猜你喜欢

转载自blog.csdn.net/paradox_1_0/article/details/89884774