nlib
msgpack/msgpack1/msgpack1.cpp

This sample reads JSON and writes it in the MessagePack (JSON) format. The sample performs the following operations.

The source code of the sample is shown below.
/*---------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)2012-2016 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. They may
not be disclosed to third parties or copied or duplicated in any form,
in whole or in part, without the prior written consent of Nintendo.
*---------------------------------------------------------------------------*/
#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() {
nlib_printf("Data in JSON format:\n%s\n\n", jsontext);
UniquePtr<MpObject> obj;
// Reads the menu data in JSON.
if (nlib_is_error(JsonStreamParser::Parse(obj, jsontext))) return false;
char data[1024];
JsonStreamGenerator gen;
JsonStreamGeneratorSettings settings;
settings.msgpack = true; // write JSON if commented out
size_t size;
if (nlib_is_error(JsonStreamGenerator::Generate(&size, data, *obj.get(), settings)))
return false;
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 ", static_cast<uint8_t>(data[i]));
}
nlib_printf("\n");
return true;
}
bool SampleMain(int, char**) { return ReadJsonWriteMessagePack(); }
NLIB_MAINFUNC