Rapidjson的簡單使用

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;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章