1
0
mirror of https://github.com/nlohmann/json synced 2024-11-22 12:00:05 +00:00
nlohmannjson/docs/examples/to_bjdata.cpp
Florian Albrechtskirchinger 9aafcbe965
Move UDLs out of the global namespace (#3605)
* Move UDLs into nlohmann::literals::json_literals namespace

* Add 'using namespace' to unit tests

* Add 'using namespace' to examples

* Add 'using namespace' to README

* Move UDL mkdocs pages out of basic_json/

* Update documentation

* Update docset index

* Add JSON_GlobalUDLs CMake option

* Add unit test

* Build examples without global UDLs

* Add CI target
2022-07-31 17:38:52 +02:00

65 lines
1.4 KiB
C++

#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
// function to print BJData's diagnostic format
void print_byte(uint8_t byte)
{
if (32 < byte and byte < 128)
{
std::cout << (char)byte;
}
else
{
std::cout << (int)byte;
}
}
int main()
{
// create a JSON value
json j = R"({"compact": true, "schema": false})"_json;
// serialize it to BJData
std::vector<std::uint8_t> v = json::to_bjdata(j);
// print the vector content
for (auto& byte : v)
{
print_byte(byte);
}
std::cout << std::endl;
// create an array of numbers
json array = {1, 2, 3, 4, 5, 6, 7, 8};
// serialize it to BJData using default representation
std::vector<std::uint8_t> v_array = json::to_bjdata(array);
// serialize it to BJData using size optimization
std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);
// serialize it to BJData using type optimization
std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);
// print the vector contents
for (auto& byte : v_array)
{
print_byte(byte);
}
std::cout << std::endl;
for (auto& byte : v_array_size)
{
print_byte(byte);
}
std::cout << std::endl;
for (auto& byte : v_array_size_and_type)
{
print_byte(byte);
}
std::cout << std::endl;
}