Rapidjson的简单使用

  • Post author:
  • Post category:其他

Rapidjson的简单使用

一、rapidjson的构造

1.1 Addmember构造

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

    // 添加name, value
    const char* name = "success_url";
    const char* value = "https://www.google.com";
    document.AddMember(rapidjson::StringRef(name), rapidjson::StringRef(value), document.GetAllocator());

    // 添加json object
    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 array
    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.AddMember(rapidjson::StringRef(jsonArrayName), array_objects, document.GetAllocator());

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    document.Accept(writer);
    std::string json = std::string(buffer.GetString());
    LOGD("testAddMember = %s", json.c_str());

1.2 用writer构造

    rapidjson::StringBuffer s;
    rapidjson::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();
    std::cout << s.GetString() << std::endl;

二、rapidjson查询

2.1 获取整个json字符串

    std::string json = std::string(buffer.GetString());

2.2 查询Value

假设现有一个json文件。

const char* json  = {
    "hello": "world",
    "t": true ,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}
  • 解析为一个document
#include "rapidjson/document.h" 
using namespace rapidjson;

Document document;
document.Parse(json);
  • 判断是否是一个object:document.IsObject()
  • 判断是否有成员hello:document.HasMember(“hello”)
  • 判断是否是字符串:document[“hello”].IsString()
  • 获取字符串:document[“hello”].GetString()
  • 判断是否是bool类型:document[“t”].IsBool()
  • 获取bool值:document[“t”].GetBool()
  • 判断是否为null:document[“n”].IsNull()
  • document[“i”].IsNumber()
  • document[“i”].IsInt()
  • document[“i”].GetInt()
  • document[“pi”].IsDouble()
  • document[“pi”].GetDouble()

2.2 查询Array

  • 方式一:
const Value& a = document["a"];
assert(a.IsArray());
for (SizeType i = 0; i < a.Size(); i++) // 使用 SizeType 而不是 size_t
        printf("a[%d] = %d\n", i, a[i].GetInt());
  • 方式二:
for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
    printf("%d ", itr->GetInt());
  • 方式三:
for (auto& v : a.GetArray())
    printf("%d ", v.GetInt());

2.3 查询object

  • 方式一:
static const char* kTypeNames[] = 
    { "Null", "False", "True", "Object", "Array", "String", "Number" };
for (Value::ConstMemberIterator itr = document.MemberBegin();
    itr != document.MemberEnd(); ++itr)
{
    printf("Type of member %s is %s\n",
        itr->name.GetString(), kTypeNames[itr->value.GetType()]);
}
  • 方式二:
Value::ConstMemberIterator itr = document.FindMember("hello");
if (itr != document.MemberEnd())
    printf("%s\n", itr->value.GetString());
  • 方式三:
for (auto& m : document.GetObject())
    printf("Type of member %s is %s\n",
        m.name.GetString(), kTypeNames[m.value.GetType()]);

2.4 查询Number

查询 获取
bool IsNumber() 不适用
bool IsUint() unsigned GetUint()
bool IsInt() int GetInt()
bool IsUint64() uint64_t GetUint64()
bool IsInt64() int64_t GetInt64()
bool IsDouble() double GetDouble()

2.5 查询String

  • GetString() 获取字符串
  • GetStringLength() 获取字符串长度

三、rapidjson修改

3.1 改变value值

  • 方式一:
    采用SetXXX或赋值操作实现
Document d; // Null
d.SetObject();
 
Value v;    // Null
v.SetInt(10);
v = 10;     // 简写,和上面的相同

方式二:

Value b(true);    // 调用 Value(bool)
Value i(-123);    // 调用 Value(int)
Value u(123u);    // 调用 Value(unsigned)
Value d(1.5);     // 调用 Value(double)

Value o(kObjectType);      //object
Value a(kArrayType);       //array

3.2 修改String

Value s;
s.SetString("rapidjson");    // 可包含空字符,长度在编译期推导
s = "rapidjson";             // 上行的缩写

3.3 修改Array

包含接口:

  • Clear()
  • Reserve(SizeType, Allocator&)
  • Value& PushBack(Value&, Allocator&)
  • template GenericValue& PushBack(T, Allocator&)
  • Value& PopBack()
  • ValueIterator Erase(ConstValueIterator pos)
  • ValueIterator Erase(ConstValueIterator first, ConstValueIterator last)
Value a(kArrayType);
Document::AllocatorType& allocator = document.GetAllocator();
 
for (int i = 5; i <= 10; i++)
    a.PushBack(i, allocator);   // 可能需要调用 realloc() 所以需要 allocator
 
// 流畅接口(Fluent interface)
a.PushBack("Lua", allocator).PushBack("Mio", allocator);

3.4 修改Object

Object 是键值对的集合。每个键必须为 String。要修改 Object,方法是增加或移除成员。以下的 API 用来增加成员:

  • Value& AddMember(Value&, Value&, Allocator& allocator)
  • Value& AddMember(StringRefType, Value&, Allocator&)
  • template Value& AddMember(StringRefType, T value, Allocator&)
  • bool RemoveMember(const Ch* name):使用键名来移除成员(线性时间复杂度)。
  • bool RemoveMember(const Value& name):除了 name 是一个 Value,和上一行相同。
  • MemberIterator RemoveMember(MemberIterator):使用迭代器移除成员(_ 常数 _ 时间复杂度)。
  • MemberIterator EraseMember(MemberIterator):和上行相似但维持成员次序(线性时间复杂度)。
  • MemberIterator EraseMember(MemberIterator first, MemberIterator last):移除一个范围内的成员,维持次序(线性时间复杂度)。
Value contact(kObject);
contact.AddMember("name", "Milo", document.GetAllocator());
contact.AddMember("married", true, document.GetAllocator());

3.5 深拷贝

CopyFrom()

3.6 交换值

Swap()

Value a(123);
Value b("Hello");
a.Swap(b);

3.7 遍历json内容

#include<iostream>
#include"rapidjson/document.h"
#include"rapidjson/writer.h"
#include"rapidjson/stringbuffer.h"
#include<string>

using namespace rapidjson;
using namespace std;

int main()

{

    string strJsonTest = "{\"item_1\":\"value_1\",\"item_2\":\"value_2\",\"item_3\":\"value_3\",\"item_4\":\"value_4\",\"item_arr\":[\"arr_vaule_1\",\"arr_vaule_2\"]}";
	Document docTest;
	docTest.Parse<0>(strJsonTest.c_str());

	if (!docTest.HasParseError())
	{
		for (rapidjson::Value::ConstMemberIterator itr = docTest.MemberBegin(); itr != docTest.MemberEnd(); itr++)
		{
			Value jKey;
			Value jValue;
			Document::AllocatorType allocator;
			jKey.CopyFrom(itr->name, allocator);
			jValue.CopyFrom(itr->value, allocator);
			if (jKey.IsString())
			{
				string name = jKey.GetString();
				printf("\r\nname: %s\r\n", name.c_str());
			}

			if (jValue.IsString())
			{
				std::cout << "jValue" << jValue.GetString() << std::endl;
			}
		}
	}


	return 0;

}



版权声明:本文为u012477435原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。