MbedJSONValue library example

Dependencies:   MbedJSONValue mbed

main.cpp

Committer:
hillkim7
Date:
2015-01-22
Revision:
0:6c7d76010005

File content as of revision 0:6c7d76010005:

#include "mbed.h"
#include "MbedJSONValue.h"

/*
* The MbedJSONValue is memory hungry class as I think.
* If your platform has enough SRAM, you can go for it.
* The library itself works fine but user need to caution using it.
* It's fine with this:
*  MbedJSONValue &ele = demo["menu"]["popup"]["menuitem"][i];
* It's big problem with this(without &):
*  MbedJSONValue ele = demo["menu"]["popup"]["menuitem"][i];
*/
void parse() {
    MbedJSONValue demo;

    const char *json = "{\"string\": \"it works\", \"number\": 3.14, \"integer\":5}";

    parse(demo, json);
    printf("string =%s\r\n" , demo["string"].get<string>().c_str());
    printf("number =%f\r\n" , demo["number"].get<double>());
    printf("integer =%d\r\n" , demo["integer"].get<int>());
}

void serialize() {
    MbedJSONValue v;
    MbedJSONValue inner;
    string val = "tt";

    v["aa"] = val;
    v["bb"] = 1.66;
    inner["test"] = true;
    inner["integer"] =  1.0;
    v["inner"] =  inner;

    string str = v.serialize();
    printf("serialized content = %s\r\n" ,  str.c_str());
}

void advanced() {
    MbedJSONValue demo;
    const char *jsonsoure =
        "{\"menu\": {"
        "\"id\": \"f\","
        "\"popup\": {"
        "  \"menuitem\": ["
        "    {\"v\": \"0\"},"
        "    {\"v\": \"1\"},"
        "    {\"v\": \"2\"}"
        "   ]"
        "  }"
        "}"
        "}";

    std::string err;
    parse(demo, jsonsoure, jsonsoure + strlen(jsonsoure), &err);
    printf("res error? %s\r\n", err.c_str());

    printf("id =%s\r\n", demo["menu"]["id"].get<string>().c_str());

    for (int i = 0; i < demo["menu"]["popup"]["menuitem"].size(); ++i) {
        MbedJSONValue &ele = demo["menu"]["popup"]["menuitem"][i];
        const string &s = ele["v"].get<string>();

        printf("menu item value =%s\r\n",s.c_str());
    }

    printf("serialized content = %s\r\n" , demo.serialize().c_str());
}

int main() {
    printf("Starting MbedJSON\r\n");
    printf(">>> parsing \r\n");
    parse();
    printf(">>> serializing \r\n");
    serialize();
    printf(">>> advanced parsing \r\n");
    advanced();
    printf("Ending MbedJSON\r\n");
}