This sample reads JSON and writes in MessagePack. The sample performs the following operations.
-
Constructs an
MpObject
from the JSON string using JsonReader::Read
.
-
Initializes
MpWriter
to write to VectorOutputStream
.
-
Writes the
MpObject
using MpWriter
after converting from JSON to MessagePack format.
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() {
MpObject obj;
if (JsonReader::ReadEx(&obj, jsontext) != 0) return false;
MpWriter writer;
ReallocOutputStream ostr;
writer.Init(&ostr);
writer.Write(obj);
writer.Close();
ostr.Flush();
if (!writer || !ostr) return false;
ReallocOutputStream::UniquePtrType data;
size_t size = ostr.Release(&data);
for (size_t i = 0; i < size; ++i) {
if (i % 16 == 0)
nlib_printf(
"\n%04x: ", static_cast<int>(i));
}
return true;
}
bool SampleMain(int, char**) { return ReadJsonWriteMessagePack(); }
NLIB_MAINFUNC