GameCorder.net

このエントリーをはてなブックマークに追加

example about array of objects in rapidjson

Example about array of objects in rapidjson.
First create array of objects.
I want to create string just like json format...


{
    "devices":[
        {
            "name":"me",
            “id”:"fasfafafafa",
            "is_host":true
        },
        {
            "name":"ma",
            “id”:"mamama",
            "is_host":false
        },
    ]
}
		

In example,there are two objects in array name "devices"
And devices have members
name is string
id is string
is_host is bool

Let's create array of objects in rapidjson
See below example


rapidjson::Document jsonDoc; 
jsonDoc.SetObject(); 
// 1.devices array
rapidjson::Value devices(rapidjson::Type::kArrayType);

// search bleDevices and create json format string
for (auto& device : bleDevices) {
    BleDevice* bleDevice = device.second;
    // 2.create object type
    rapidjson::Value object(rapidjson::Type::kObjectType);
    // name
    rapidjson::Value key(NAME_KEY.c_str(),jsonDoc.GetAllocator());
    rapidjson::Value name(bleDevice->getName().c_str(),jsonDoc.GetAllocator());
    object.AddMember(key, name, jsonDoc.GetAllocator());
    // id
    key.SetString(rapidjson::StringRef(ID_KEY));
    //value.SetString(rapidjson::StringRef(bleDevice->getUuid().c_str()));
    rapidjson::Value id(bleDevice->getUuid().c_str(),jsonDoc.GetAllocator());
    object.AddMember(key,id,jsonDoc.GetAllocator());
    // is_host
    key.SetString(rapidjson::StringRef(HOST_KEY));
    rapidjson::Value isHost;
    // 3.bool value
    isHost.SetBool(bleDevice->getIsHost());
    object.AddMember(key,isHost,jsonDoc.GetAllocator());
    // 4.push array
    devices.PushBack(object,jsonDoc.GetAllocator());
}
// 5.put name devices which are array
jsonDoc.AddMember("devices",devices,jsonDoc.GetAllocator());
// to Serialize to JSON String
rapidjson::StringBuffer sb;
rapidjson::Writer writer(sb);
jsonDoc.Accept(writer);
// 6.get json format string
string jsonString = sb.GetString();
		

create array of objects in rapidjson

1.devices array
devices are array so use rapidjson type kArrayType.

2.create object type
devices are object so create object type.
Name is kObjectType.
And create key and value and set this object.
Next push array name devices and so on.

In Class BleDevice has is_host
is_host is about host or Client in bluetooth.
is_host is bool value.
rapidjson can deal with bool value.
In this case,keyword is true or false.

To use setBool.
create value "true" or "false"

4.push array
push object into array name devices.

5.put name devices which are array yes add member devices

6.get json format string Use StringBuffer create json string.