nlib
msgpack/msgpack1/msgpack1.cpp

This sample reads JSON and writes in MessagePack. The sample performs the following operations.

The source code of the sample is shown below.

using nlib_ns::msgpack::JsonReader;
using nlib_ns::msgpack::MpWriter;
using nlib_ns::msgpack::MpObject;
const char jsontext[] =
"{ \"item\": ["
"{\"itemCode\":91, \"itemName\" : \"ramen with salt based soup\", \"itemPrice\":300},"
"{\"itemCode\":94, \"itemName\" : \"ramen with miso based soup\", \"itemPrice\":290}, "
"{\"itemCode\":95, \"itemName\" : \"ramen with a pork bone broth\", \"itemPrice\":320} "
"] } ";
bool ReadJsonWriteMessagePack() {
nlib_printf("Data in JSON format:\n%s\n\n", jsontext);
MpObject obj;
// Reads the menu data in JSON.
if (JsonReader::ReadEx(&obj, jsontext) != 0) return false;
MpWriter writer;
ReallocOutputStream ostr;
writer.Init(&ostr);
writer.Write(obj);
writer.Close(); // writer.Close() detaches ostr, but does not close ostr.
ostr.Flush();
if (!writer || !ostr) return false;
ReallocOutputStream::UniquePtrType data;
size_t size = ostr.Release(&data);
nlib_printf("Data in MessagePack format:\n");
nlib_printf("size = %" PRIuS " bytes\n", size);
for (size_t i = 0; i < size; ++i) {
if (i % 16 == 0) nlib_printf("\n%04x: ", static_cast<int>(i));
nlib_printf("%02x ", data[i]);
}
nlib_printf("\n");
return true;
}
bool SampleMain(int, char**) { return ReadJsonWriteMessagePack(); }
NLIB_MAINFUNC