Cjson Common usage

Source: Internet
Author: User
Tags string back text to json

Cjson is a very lightweight JSON data parsing and building of Oss.

It's easy to build a json-formatted string in C Code. You can also convert the JSON string to Cjson object as defined in Cjson.

Usually used in, mobile phone browser or app to send a JSON data to the platform, the platform is running C code, the platform needs to convert the JSON string to Cjson object, and then parse the contents of the JSON into a C structure, after the final processing, Build a JSON string back to the phone browser and app.

At the same time, it can be used to build a simple JSON RPC mechanism, in the Client's API to convert the function name and parameters into a JSON string, on the server side to parse the JSON string to do Processing.

Cjson contains only two files Cjson.c and CJSON.H. We can embed it directly into the code when we use it, or we can compile the Cjson into so and use it.

Cjson's own sample code is a more comprehensive example of Cjson Usage. So you don't write your own sample.

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"

/* Parse Text to JSON, then render back to text, and print! */
void doit (char *text)
{
Char *out;cjson *json;

Json=cjson_parse (text);//parse the string into JSON object.
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. */
void Dofile (char *filename)
{
FILE *f;long Len;char *data;

F=fopen (filename, "rb"); fseek (f,0,seek_end); len=ftell (f); fseek (f,0,seek_set);//calculate file Length.
Data= (char*) malloc (len+1); fread (data,1,len,f); fclose (f);
Doit (data);
Free (data);
}

/* used by some code below as an example Datatype. */
struct Record {

const CHAR *precision;

Double lat,lon;

const CHAR *address,*city,*state,*zip,*country;

};

/* Create a bunch of objects as Demonstration. */
void Create_objects ()
{
Cjson *root,*fmt,*img,*thm,*fld;char *out;int i;/* Declare a FEW. */
/* our ' Days of the week ' array: */
const char *strings[7]={"Sunday", "Monday", "tuesday", "wednesday", "thursday", "Friday", "Saturday"};
/* our matrix: */
int numbers[3][3]={{0,-1,0},{1,0,0},{0,0,1}};
/* our "gallery" item: */
int ids[4]={116,943,234,38793};
/* our array of "records": */
struct record fields[2]={
{"zip", 37.7668,-1.223959e+2, "", "SAN FRANCISCO", "CA", "94107", "US"},
{"zip", 37.371991,-1.22026e+2, "", "SUNNYVALE", "CA", "94085", "US"}

};

/* Here we construct some JSON standards, from the JSON Site. */

/* our "Video" datatype: */

The JSON data is built as Follows:

Root=cjson_createobject ();
Cjson_additemtoobject (root, "name", cjson_createstring ("Jack (\" bee\ ") nimble"));
Cjson_additemtoobject (root, "format", Fmt=cjson_createobject ());
Cjson_addstringtoobject (fmt, "type", "rect");
Cjson_addnumbertoobject (fmt, "width", 1920);
Cjson_addnumbertoobject (fmt, "height", 1080);
Cjson_addfalsetoobject (fmt, "interlace");
Cjson_addnumbertoobject (fmt, "frame rate", 24);


Out=cjson_print (root), cjson_delete (root);p rintf ("%s\n", out);/* Print to text, Delete the cjson, print it, Release the String. */

/* our ' Days of the week ' array: */

The JSON data is built as Follows:

Root=cjson_createstringarray (strings,7);

Out=cjson_print (root), cjson_delete (root);p rintf ("%s\n", out);

/* our matrix: */

The JSON data is built as Follows:

Root=cjson_createarray ();

For (i=0;i<3;i++) Cjson_additemtoarray (root,cjson_createintarray (numbers[i],3));

/*cjson_replaceiteminarray (root,1,cjson_createstring ("replacement")); */

Out=cjson_print (root), cjson_delete (root);p rintf ("%s\n", out);


/* our "gallery" item: */

The JSON data is built as Follows:

Root=cjson_createobject ();

Cjson_additemtoobject (root, "Image", Img=cjson_createobject ());
Cjson_addnumbertoobject (img, "Width", 800);
Cjson_addnumbertoobject (img, "Height", 600);
Cjson_addstringtoobject (img, "Title", "View from 15th floor");
Cjson_additemtoobject (img, "Thumbnail", Thm=cjson_createobject ());
Cjson_addstringtoobject (thm, "Url", "http:/*www.example.com/image/481989943");
Cjson_addnumbertoobject (thm, "Height", 125);
Cjson_addstringtoobject (thm, "Width", "100");
Cjson_additemtoobject (img, "IDs", Cjson_createintarray (ids,4));

Out=cjson_print (root), cjson_delete (root);p rintf ("%s\n", out);

/* our array of "records": */

The JSON data is built as Follows:

Root=cjson_createarray ();

For (i=0;i<2;i++)
{
Cjson_additemtoarray (root,fld=cjson_createobject ());
Cjson_addstringtoobject (fld, "precision", fields[i].precision);
Cjson_addnumbertoobject (fld, "Latitude", fields[i].lat);
Cjson_addnumbertoobject (fld, "longitude", fields[i].lon);
Cjson_addstringtoobject (fld, "Address", fields[i].address);
Cjson_addstringtoobject (fld, "city", fields[i].city);
Cjson_addstringtoobject (fld, "state", fields[i].state);
Cjson_addstringtoobject (fld, "Zip", fields[i].zip);
Cjson_addstringtoobject (fld, "country", fields[i].country);
}

/*cjson_replaceiteminobject (cjson_getarrayitem (root,1), "city", cjson_createintarray (ids,4)); */

Out=cjson_print (root), cjson_delete (root);p rintf ("%s\n", out);

}

int main (int argc, const char * Argv[]) {
/* a bunch of json: */
Char text1[]= "{\n\" name\ ": \" Jack (\\\ "bee\\\") nimble\ ", \n\" format\ ": {\" type\ ": \" rect\ ", \n\" width\ ": 1920x1080, \n\" height\ ": \n\," interlace\ ": false,\" frame rate\ ": 24\n}\n}";
Char text2[]= "[\" sunday\ ", \" monday\ ", \" tuesday\ ", \" wednesday\ ", \" thursday\ ", \" friday\ ", \" saturday\ "]";
Char text3[]= "[\ n [0,-1, 0],\n [1, 0, 0],\n [0, 0, 1]\n]\n];
Char text4[]= "{\n\" image\ ": {\n\" width\ ": 800,\n\" height\ ": 600,\n\" title\ ": \" View from 15th floor\ ", \n\" thumbnail\ ": {\n\ "url\": \ "http:/*www.example.com/image/481989943\", \n\ "height\": 125,\n\ "width\": \ "100\" \n},\n\ "IDs\": [116, 943, 234, 38793]\n}\n} ";
char text5[]= "[\ n \ n \" precision\ ": \" zip\ ", \ n \" latitude\ ": 37.7668,\n \" longitude\ ": -122.3959,\n \" address\ ": \" \ ", \ n \ "city\": \ "SAN francisco\", \ n \ "state\": \ "ca\", \ n \ "zip\": \ "94107\", \ n \ "country\": \ "us\" \ n},\n {\ n \ "precision\": \ "zip\", \ n \ "latitude\": 37.371991,\n \ "longitude\": -122.026020,\n \ "address\": \ "\", \ n \ "city\": \ "sunnyvale\", \ n \ " State\ ": \" ca\ ", \ n \" zip\ ": \" 94085\ ", \ n \" country\ ": \" us\ "\ n}\n]";

/* Process each JSON TextBlock by parsing and then Rebuilding: */
Doit (text1);
Doit (text2);
Doit (text3);
Doit (text4);
Doit (text5);

/* Parse Standard Testfiles: */
/*dofile (".. /.. /tests/test1 "); */
/*dofile (".. /.. /tests/test2 "); */
/*dofile (".. /.. /tests/test3 "); */
/*dofile (".. /.. /tests/test4 "); */
/*dofile (".. /.. /tests/test5 "); */

/* now some samplecode for building objects concisely: */
Create_objects ();

Return 0;
}

Most of the above sample is the process of string building Cjson Object. Let's look at how to parse the item in Cjson Object.

int main (int argc, const char * Argv[]) {
/* a bunch of json: */
Char text1[]= "{\n\" name\ ": \" Jack (\\\ "bee\\\") nimble\ ", \n\" format\ ": {\" type\ ": \" rect\ ", \n\" width\ ": 1920x1080, \n\" height\ ": \n\," interlace\ ": false,\" frame rate\ ": 24\n}\n}";
Char *out;cjson *json;

Json=cjson_parse (text1);
If (!json) {printf ("Error before: [%s]\n", cjson_geterrorptr ());}
Else
{
Out=cjson_print (json);
Cjson *name = NULL;
Name = Cjson_getobjectitem (json, "name");
printf ("name:%s\n", name->valuestring);
Cjson *fmt = Cjson_getobjectitem (json, "format");
printf ("fmt:type:%s\n", Cjson_getobjectitem (fmt, "type")->valuestring);
printf ("fmt:width:%d\n", Cjson_getobjectitem (fmt, "width")->valueint);
printf ("fmt:height:%d\n", Cjson_getobjectitem (fmt, "height")->valueint);
printf ("fmt:interlacetype:%d\n", Cjson_getobjectitem (fmt, "interlace")->type);
If (cjson_getobjectitem (fmt, "interlace")->type = = (int) Cjson_false)
printf ("fmt:interlace:false\n");
else if (cjson_getobjectitem (fmt, "interlace")->type = = (int) Cjson_true)
printf ("fmt:interlace:true\n");
printf ("fmt:frame rate:%d\n", cjson_getobjectitem (fmt, "frame rate")->valueint);
Cjson_delete (json);
printf ("%s\n", out);
Free (out);
}


Return 0;
}

The output results are as follows:

Cjson Common usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.