Sample program using picojson library. Note: it seems that there are some memory? issues with \"complex\" structures. So always test your json with the lib before using it within your application.
main.cpp
00001 #include "mbed.h" 00002 #include "picojson.h" 00003 00004 00005 void parse() { 00006 picojson::value v; 00007 const char *json = "{\"string\": \"it works\", \"number\": 3.14, \"integer\":5}"; 00008 00009 string err = picojson::parse(v, json, json + strlen(json)); 00010 printf("res error? %s\r\n", err.c_str()); 00011 printf("string =%s\r\n" , v.get("string").get<string>().c_str()); 00012 printf("number =%f\r\n" , v.get("number").get<double>()); 00013 printf("integer =%d\r\n" , (int)v.get("integer").get<double>()); 00014 } 00015 00016 void serialize() { 00017 picojson::object v; 00018 picojson::object inner; 00019 string val = "tt"; 00020 00021 v["aa"] = picojson::value(val); 00022 v["bb"] = picojson::value(1.66); 00023 inner["test"] = picojson::value(true); 00024 inner["integer"] = picojson::value(1.0); 00025 v["inner"] = picojson::value(inner); 00026 00027 string str = picojson::value(v).serialize(); 00028 printf("serialized content = %s\r\n" , str.c_str()); 00029 } 00030 00031 void advanced() { 00032 picojson::value v; 00033 const char *jsonsoure = 00034 "{\"menu\": {" 00035 "\"id\": \"f\"," 00036 "\"popup\": {" 00037 " \"menuitem\": [" 00038 " {\"v\": \"0\"}," 00039 " {\"v\": \"1\"}," 00040 " {\"v\": \"2\"}" 00041 " ]" 00042 " }" 00043 "}" 00044 "}"; 00045 char * json = (char*) malloc(strlen(jsonsoure)+1); 00046 strcpy(json, jsonsoure); 00047 string err = picojson::parse(v, json, json + strlen(json)); 00048 printf("res error? %s\r\n", err.c_str()); 00049 00050 printf("id =%s\r\n", v.get("menu").get("id").get<string>().c_str()); 00051 00052 picojson::array list = v.get("menu").get("popup").get("menuitem").get<picojson::array>(); 00053 00054 for (picojson::array::iterator iter = list.begin(); iter != list.end(); ++iter) { 00055 printf("menu item value =%s\r\n", (*iter).get("v").get<string>().c_str()); 00056 } 00057 } 00058 00059 int main() { 00060 printf("Starting PicoJSONSample "__TIME__"\r\n"); 00061 printf(">>> parsing \r\n"); 00062 parse(); 00063 printf(">>> serializing \r\n"); 00064 serialize(); 00065 printf(">>> advanced parsing \r\n"); 00066 advanced(); 00067 printf("Ending PicoJSONSample " __TIME__ "\r\n"); 00068 }
Generated on Tue Jul 12 2022 22:41:19 by 1.7.2