This sample reads JSON and writes it in the MessagePack (JSON) format. The sample performs the following operations.
-
Constructs an
MpObject
from the JSON string using JsonStreamParser::Parse()
.
-
Writes it to the memory in the
MessagePack
format using JsonStreamGenerator::Generate()
.
- The source code of the sample is shown below.
#include "nn/nlib/msgpack/JsonStreamParser.h"
#include "nn/nlib/msgpack/JsonStreamGenerator.h"
using nlib_ns::msgpack::MpObject;
using nlib_ns::msgpack::JsonStreamParser;
using nlib_ns::msgpack::JsonStreamGenerator;
using nlib_ns::msgpack::JsonStreamGeneratorSettings;
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() {
UniquePtr<MpObject> obj;
if (
nlib_is_error(JsonStreamParser::Parse(obj, jsontext)))
return false;
char data[1024];
JsonStreamGenerator gen;
JsonStreamGeneratorSettings settings;
settings.msgpack = true;
size_t size;
if (
nlib_is_error(JsonStreamGenerator::Generate(&size, data, *obj.get(), settings)))
return false;
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