Cjson Use Cases
After understanding the data structure, interface and implementation of Cjson, let's illustrate its use.
This example is a simple management of student information forms, and we add element information to the JSON by means of key-value pairs.
The output can then be formatted and the original Cjson object will be generated in reverse from the string output.
intTest_cjson () {Cjson* Proot =Cjson_createobject (); Cjson* Parray =Cjson_createarray (); Cjson_additemtoobject (Proot,"Students_info", Parray); Char* Szout =Cjson_print (Proot); Cjson* Pitem =Cjson_createobject (); Cjson_addstringtoobject (Pitem,"name","chenzhongjing"); Cjson_addstringtoobject (Pitem,"Sex","male"); Cjson_addnumbertoobject (Pitem," Age", -); Cjson_additemtoarray (Parray, Pitem); Pitem=Cjson_createobject (); Cjson_addstringtoobject (Pitem,"name","Fengxuan"); Cjson_addstringtoobject (Pitem,"Sex","male"); Cjson_addnumbertoobject (Pitem," Age", -); Cjson_additemtoarray (Parray, Pitem); Pitem=Cjson_createobject (); Cjson_addstringtoobject (Pitem,"name","Tuhui"); Cjson_addstringtoobject (Pitem,"Sex","male"); Cjson_addnumbertoobject (Pitem," Age", A); Cjson_additemtoarray (Parray, Pitem); Char* Szjson =Cjson_print (Proot); cout<< Szjson <<Endl; Cjson_delete (Proot); //Free (Szjson);Proot=Cjson_parse (Szjson); Parray= Cjson_getobjectitem (Proot,"Students_info"); if(NULL = =Parray) { return-1; } intICount =cjson_getarraysize (Parray); for(inti =0; i < ICount; ++i) {Cjson* Pitem =Cjson_getarrayitem (Parray, i); if(NULL = =pitem) { Continue; } stringStrName = Cjson_getobjectitem (Pitem,"name"),valuestring; stringStrsex = Cjson_getobjectitem (Pitem,"Sex"),valuestring; intIage = Cjson_getobjectitem (Pitem," Age"),Valueint; } cjson_delete (Proot); Free(Szjson);}
Or for formatted strings, to Cjson management, automatic recognition, produce type output.
/*Parse Text to JSON, then render back to text, and print!*/voidDoitChar*text) { Char* out; Cjson *JSON; JSON=cjson_parse (text); if(!json) {printf ("Error before: [%s]\n", Cjson_geterrorptr ()); } Else { out=Cjson_print (JSON); Cjson_delete (JSON); printf ("%s\n", out); Free( out); }}/*Read a file, parse, render back, etc.*/voidDofile (Char*filename) {FILE*f;LongLenChar*data; F= fopen (filename,"RB"); ASSERT (f); Fseek (F,0, Seek_end); Len=Ftell (f); Fseek (F,0, Seek_set); Data= (Char*)malloc(Len +1); memset (data,0,sizeof(Char) * (len +1)); Fread (data,1, Len, F); printf ("%s", data); Fclose (f); doit (data); Free(data);}
int Main () { char"{\n\" name\ ": \" Jack (\\\ "bee\\\") nimble\ ", \n\" format\ ": {\" type\ " : \ "Rect\", \n\ "width\": 1920x1080, \n\ "height\": , \n\ "interlace\": false,\ "Frame rate\": 24\n}\n} ";
Doit (Text1);
return 0 ;
}
Cjons Serialization Tool Interpretation III (use case)