nlib
msgpack/json/json.cpp

JSONを読んで変更して書きだすサンプルです。以下のようなことを行なっています。

以下がサンプルのソースコードになります。

using nlib_ns::msgpack::JsonReader;
using nlib_ns::msgpack::JsonWriter;
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 ReadModifyWriteJson() {
MpObject obj;
// Reads the menu data in JSON.
if (JsonReader::ReadEx(&obj, jsontext) != 0) return false;
// You want to raise the prices.
MpObject* price;
int val;
MpObject* items = obj.GetMapItem("item");
if (!items) return false;
MpObject* salt = items->GetArrayItem(0);
if (!salt) return false;
price = salt->GetMapItem("itemPrice");
if (!price) return false;
if (0 != price->Unbox(&val)) return false; // Unboxes 'price' and retrieve an integer value.
val += 500; // Changes the price
if (0 != price->Box(val)) return false; // Boxes 'val' and updates 'price'.
MpObject* miso = items->GetArrayItem(1);
if (!miso) return false;
price = miso->GetMapItem("itemPrice");
if (!price) return false;
if (0 != price->Unbox(&val)) return false;
val += 500;
price->Box(val); // Boxing primitive objects never returns an error.
MpObject* pork = items->GetArrayItem(2);
if (!pork) return false;
price = pork->GetMapItem("itemPrice");
if (!price) return false;
if (0 != price->Unbox(&val)) return false;
val += 500;
// You can use the assignment operators instead of boxing
// when you box primitive objects.
*price = val;
// Writes the menu data in JSON.
char str[1024];
if (!JsonWriter::Write(str, obj)) return false;
nlib_printf("%s\n", str);
return true;
}
bool SampleMain(int, char**) { return ReadModifyWriteJson(); }
NLIB_MAINFUNC