项目文件:
chunli@Linux:~/ace/json/cJSON$tree . ├──cJSON.c ├──cJSON.h ├──main.c └──tests ├──test1 ├──test2 ├──test3 ├──test4 └──test5 1directory,8files
chunli@Linux:~/ace/json/cJSON$catcJSON.h /* Copyright(c)2009DaveGamble Permissionisherebygranted,freeofcharge,toanypersonobtainingacopy ofthissoftwareandassociateddocumentationfiles(the"Software"),todeal intheSoftwarewithoutrestriction,includingwithoutlimitationtherights touse,copy,modify,merge,publish,distribute,sublicense,and/orsell copiesoftheSoftware,andtopermitpersonstowhomtheSoftwareis furnishedtodoso,subjecttothefollowingconditions: Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedin allcopiesorsubstantialportionsoftheSoftware. THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSOR IMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHE AUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHER LIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN THESOFTWARE. */ #ifndefcJSON__h #definecJSON__h #ifdef__cplusplus extern"C" { #endif /*cJSONTypes:*/ #definecJSON_False0 #definecJSON_True1 #definecJSON_NULL2 #definecJSON_Number3 #definecJSON_String4 #definecJSON_Array5 #definecJSON_Object6 #definecJSON_IsReference256 #definecJSON_StringIsConst512 /*ThecJSONstructure:*/ typedefstructcJSON{ structcJSON*next,*prev; /*next/prevallowyoutowalkarray/objectchains.Alternatively,useGetArraySize/GetArrayItem/GetObjectItem*/ structcJSON*child; /*Anarrayorobjectitemwillhaveachildpointerpointingtoachainoftheitemsinthearray/object.*/ inttype; /*Thetypeoftheitem,asabove.*/ char*valuestring; /*Theitem'sstring,iftype==cJSON_String*/ intvalueint; /*Theitem'snumber,iftype==cJSON_Number*/ doublevaluedouble; /*Theitem'snumber,iftype==cJSON_Number*/ char*string; /*Theitem'snamestring,ifthisitemisthechildof,orisinthelistofsubitemsofanobject.*/ }cJSON; typedefstructcJSON_Hooks{ void*(*malloc_fn)(size_tsz); void(*free_fn)(void*ptr); }cJSON_Hooks; /*Supplymalloc,reallocandfreefunctionstocJSON*/ externvoidcJSON_InitHooks(cJSON_Hooks*hooks); /*SupplyablockofJSON,andthisreturnsacJSONobjectyoucaninterrogate.CallcJSON_Deletewhenfinished.*/ externcJSON*cJSON_Parse(constchar*value); /*RenderacJSONentitytotextfortransfer/storage.Freethechar*whenfinished.*/ externchar*cJSON_Print(cJSON*item); /*RenderacJSONentitytotextfortransfer/storagewithoutanyformatting.Freethechar*whenfinished.*/ externchar*cJSON_PrintUnformatted(cJSON*item); /*RenderacJSONentitytotextusingabufferedstrategy.prebufferisaguessatthefinalsize.guessingwellreducesreallocation.fmt=0givesunformatted,=1givesformatted*/ externchar*cJSON_PrintBuffered(cJSON*item,intprebuffer,intfmt); /*DeleteacJSONentityandallsubentities.*/ externvoidcJSON_Delete(cJSON*c); /*Returnsthenumberofitemsinanarray(orobject).*/ externint cJSON_GetArraySize(cJSON*array); /*Retrieveitemnumber"item"fromarray"array".ReturnsNULLifunsuccessful.*/ externcJSON*cJSON_GetArrayItem(cJSON*array,intitem); /*Getitem"string"fromobject.Caseinsensitive.*/ externcJSON*cJSON_GetObjectItem(cJSON*object,constchar*string); /*ForanalysingFailedparses.Thisreturnsapointertotheparseerror.You'llprobablyneedtolookafewcharsbacktomakesenSEOfit.DefinedwhencJSON_Parse()returns0.0whencJSON_Parse()succeeds.*/ externconstchar*cJSON_GetErrorPtr(void); /*ThesecallscreateacJSONitemoftheappropriatetype.*/ externcJSON*cJSON_CreateNull(void); externcJSON*cJSON_CreateTrue(void); externcJSON*cJSON_CreateFalse(void); externcJSON*cJSON_CreateBool(intb); externcJSON*cJSON_CreateNumber(doublenum); externcJSON*cJSON_CreateString(constchar*string); externcJSON*cJSON_CreateArray(void); externcJSON*cJSON_CreateObject(void); /*TheseutilitiescreateanArrayofcountitems.*/ externcJSON*cJSON_CreateIntArray(constint*numbers,intcount); externcJSON*cJSON_CreateFloatArray(constfloat*numbers,intcount); externcJSON*cJSON_CreateDoubleArray(constdouble*numbers,intcount); externcJSON*cJSON_CreateStringArray(constchar**strings,intcount); /*Appenditemtothespecifiedarray/object.*/ externvoidcJSON_AddItemToArray(cJSON*array,cJSON*item); externvoid cJSON_AddItemToObject(cJSON*object,constchar*string,cJSON*item); externvoid cJSON_AddItemToObjectCS(cJSON*object,cJSON*item); /*Usethiswhenstringisdefinitelyconst(i.e.aliteral,orasgoodas),andwilldefinitelysurvivethecJSONobject*/ /*Appendreferencetoitemtothespecifiedarray/object.UsethiswhenyouwanttoaddanexistingcJSONtoanewcJSON,butdon'twanttocorruptyourexistingcJSON.*/ externvoidcJSON_AddItemReferenceToArray(cJSON*array,cJSON*item); externvoid cJSON_AddItemReferenceToObject(cJSON*object,cJSON*item); /*Remove/DetatchitemsfromArrays/Objects.*/ externcJSON*cJSON_DetachItemFromArray(cJSON*array,intwhich); externvoidcJSON_DeleteItemFromArray(cJSON*array,intwhich); externcJSON*cJSON_DetachItemFromObject(cJSON*object,constchar*string); externvoidcJSON_DeleteItemFromObject(cJSON*object,constchar*string); /*Updatearrayitems.*/ externvoidcJSON_InsertItemInArray(cJSON*array,intwhich,cJSON*newitem); /*Shiftspre-existingitemstotheright.*/ externvoidcJSON_ReplaceItemInArray(cJSON*array,cJSON*newitem); externvoidcJSON_ReplaceItemInObject(cJSON*object,cJSON*newitem); /*DuplicateacJSONitem*/ externcJSON*cJSON_Duplicate(cJSON*item,intrecurse); /*Duplicatewillcreateanew,identicalcJSONitemtotheoneyoupass,innewmemorythatwill needtobereleased.Withrecurse!=0,itwillduplicateanychildrenconnectedtotheitem. Theitem->nextand->prevpointersarealwayszeroonreturnfromDuplicate.*/ /*ParseWithOptsallowsyoutorequire(andcheck)thattheJSONisnullterminated,andtoretrievethepointertothefinalbyteparsed.*/ externcJSON*cJSON_ParseWithOpts(constchar*value,constchar**return_parse_end,intrequire_null_terminated); externvoidcJSON_Minify(char*json); /*Macrosforcreatingthingsquickly.*/ #definecJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object,name,cJSON_CreateNull()) #definecJSON_AddTrueToObject(object,cJSON_CreateTrue()) #definecJSON_AddFalseToObject(object,cJSON_CreateFalse()) #definecJSON_AddBoolToObject(object,b) cJSON_AddItemToObject(object,cJSON_CreateBool(b)) #definecJSON_AddNumberToObject(object,n) cJSON_AddItemToObject(object,cJSON_CreateNumber(n)) #definecJSON_AddStringToObject(object,s) cJSON_AddItemToObject(object,cJSON_CreateString(s)) /*Whenassigninganintegervalue,itneedstobepropagatedtovaluedoubletoo.*/ #definecJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) #definecJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) #ifdef__cplusplus } #endif #endif
chunli@Linux:~/ace/json/cJSON$catcJSON.c /* Copyright(c)2009DaveGamble Permissionisherebygranted,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN THESOFTWARE. */ /*cJSON*/ /*JSONparserinC.*/ #include<string.h> #include<stdio.h> #include<math.h> #include<stdlib.h> #include<float.h> #include<limits.h> #include<ctype.h> #include"cJSON.h" staticconstchar*ep; constchar*cJSON_GetErrorPtr(void){returnep;} staticintcJSON_strcasecmp(constchar*s1,constchar*s2) { if(!s1)return(s1==s2)?0:1;if(!s2)return1; for(;tolower(*s1)==tolower(*s2);++s1,++s2) if(*s1==0) return0; returntolower(*(constunsignedchar*)s1)-tolower(*(constunsignedchar*)s2); } staticvoid*(*cJSON_malloc)(size_tsz)=malloc; staticvoid(*cJSON_free)(void*ptr)=free; staticchar*cJSON_strdup(constchar*str) { size_tlen; char*copy; len=strlen(str)+1; if(!(copy=(char*)cJSON_malloc(len)))return0; memcpy(copy,str,len); returncopy; } voidcJSON_InitHooks(cJSON_Hooks*hooks) { if(!hooks){/*Resethooks*/ cJSON_malloc=malloc; cJSON_free=free; return; } cJSON_malloc=(hooks->malloc_fn)?hooks->malloc_fn:malloc; cJSON_free =(hooks->free_fn)?hooks->free_fn:free; } /*Internalconstructor.*/ staticcJSON*cJSON_New_Item(void) { cJSON*node=(cJSON*)cJSON_malloc(sizeof(cJSON)); if(node)memset(node,sizeof(cJSON)); returnnode; } /*DeleteacJSONstructure.*/ voidcJSON_Delete(cJSON*c) { cJSON*next; while(c) { next=c->next; if(!(c->type&cJSON_IsReference)&&c->child)cJSON_Delete(c->child); if(!(c->type&cJSON_IsReference)&&c->valuestring)cJSON_free(c->valuestring); if(!(c->type&cJSON_StringIsConst)&&c->string)cJSON_free(c->string); cJSON_free(c); c=next; } } /*Parsetheinputtexttogenerateanumber,andpopulatetheresultintoitem.*/ staticconstchar*parse_number(cJSON*item,constchar*num) { doublen=0,sign=1,scale=0;intsubscale=0,signsubscale=1; if(*num=='-')sign=-1,num++; /*Hassign?*/ if(*num=='0')num++; /*iszero*/ if(*num>='1'&&*num<='9') do n=(n*10.0)+(*num++-'0'); while(*num>='0'&&*num<='9'); /*Number?*/ if(*num=='.'&&num[1]>='0'&&num[1]<='9'){num++; do n=(n*10.0)+(*num++-'0'),scale--;while(*num>='0'&&*num<='9');} /*Fractionalpart?*/ if(*num=='e'||*num=='E') /*Exponent?*/ { num++;if(*num=='+')num++; elseif(*num=='-')signsubscale=-1,num++; /*Withsign?*/ while(*num>='0'&&*num<='9')subscale=(subscale*10)+(*num++-'0'); /*Number?*/ } n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /*number=+/-number.fraction*10^+/-exponent*/ item->valuedouble=n; item->valueint=(int)n; item->type=cJSON_Number; returnnum; } staticintpow2gt(intx) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; returnx+1; } typedefstruct{char*buffer;intlength;intoffset;}printbuffer; staticchar*ensure(printbuffer*p,intneeded) { char*newbuffer;intnewsize; if(!p||!p->buffer)return0; needed+=p->offset; if(needed<=p->length)returnp->buffer+p->offset; newsize=pow2gt(needed); newbuffer=(char*)cJSON_malloc(newsize); if(!newbuffer){cJSON_free(p->buffer);p->length=0,p->buffer=0;return0;} if(newbuffer)memcpy(newbuffer,p->buffer,p->length); cJSON_free(p->buffer); p->length=newsize; p->buffer=newbuffer; returnnewbuffer+p->offset; } staticintupdate(printbuffer*p) { char*str; if(!p||!p->buffer)return0; str=p->buffer+p->offset; returnp->offset+strlen(str); } /*Renderthenumbernicelyfromthegivenitemintoastring.*/ staticchar*print_number(cJSON*item,printbuffer*p) { char*str=0; doubled=item->valuedouble; if(d==0) { if(p) str=ensure(p,2); else str=(char*)cJSON_malloc(2); /*specialcasefor0.*/ if(str)strcpy(str,"0"); } elseif(fabs(((double)item->valueint)-d)<=DBL_EPSILON&&d<=INT_MAX&&d>=INT_MIN) { if(p) str=ensure(p,21); else str=(char*)cJSON_malloc(21); /*2^64+1canberepresentedin21chars.*/ if(str) sprintf(str,"%d",item->valueint); } else { if(p) str=ensure(p,64); else str=(char*)cJSON_malloc(64); /*Thisisanicetradeoff.*/ if(str) { if(fabs(floor(d)-d)<=DBL_EPSILON&&fabs(d)<1.0e60)sprintf(str,"%.0f",d); elseif(fabs(d)<1.0e-6||fabs(d)>1.0e9) sprintf(str,"%e",d); else sprintf(str,"%f",d); } } returnstr; } staticunsignedparse_hex4(constchar*str) { unsignedh=0; if(*str>='0'&&*str<='9')h+=(*str)-'0';elseif(*str>='A'&&*str<='F')h+=10+(*str)-'A';elseif(*str>='a'&&*str<='f')h+=10+(*str)-'a';elsereturn0; h=h<<4;str++; if(*str>='0'&&*str<='9')h+=(*str)-'0';elseif(*str>='A'&&*str<='F')h+=10+(*str)-'A';elseif(*str>='a'&&*str<='f')h+=10+(*str)-'a';elsereturn0; h=h<<4;str++; if(*str>='0'&&*str<='9')h+=(*str)-'0';elseif(*str>='A'&&*str<='F')h+=10+(*str)-'A';elseif(*str>='a'&&*str<='f')h+=10+(*str)-'a';elsereturn0; h=h<<4;str++; if(*str>='0'&&*str<='9')h+=(*str)-'0';elseif(*str>='A'&&*str<='F')h+=10+(*str)-'A';elseif(*str>='a'&&*str<='f')h+=10+(*str)-'a';elsereturn0; returnh; } /*Parsetheinputtextintoanunescapedcstring,andpopulateitem.*/ staticconstunsignedcharfirstByteMark[7]={0x00,0x00,0xC0,0xE0,0xF0,0xF8,0xFC}; staticconstchar*parse_string(cJSON*item,constchar*str) { constchar*ptr=str+1;char*ptr2;char*out;intlen=0;unsigneduc,uc2; if(*str!='\"'){ep=str;return0;} /*notastring!*/ while(*ptr!='\"'&&*ptr&&++len)if(*ptr++=='\\')ptr++; /*Skipescapedquotes.*/ out=(char*)cJSON_malloc(len+1); /*Thisishowlongweneedforthestring,roughly.*/ if(!out)return0; ptr=str+1;ptr2=out; while(*ptr!='\"'&&*ptr) { if(*ptr!='\\')*ptr2++=*ptr++; else { ptr++; switch(*ptr) { case'b':*ptr2++='\b'; break; case'f':*ptr2++='\f'; break; case'n':*ptr2++='\n'; break; case'r':*ptr2++='\r'; break; case't':*ptr2++='\t'; break; case'u': /*transcodeutf16toutf8.*/ uc=parse_hex4(ptr+1);ptr+=4; /*gettheunicodechar.*/ if((uc>=0xDC00&&uc<=0xDFFF)||uc==0) break; /*checkforinvalid. */ if(uc>=0xD800&&uc<=0xDBFF) /*UTF16surrogatepairs. */ { if(ptr[1]!='\\'||ptr[2]!='u') break; /*missingsecond-halfofsurrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if(uc2<0xDC00||uc2>0xDFFF) break; /*invalidsecond-halfofsurrogate. */ uc=0x10000+(((uc&0x3FF)<<10)|(uc2&0x3FF)); } len=4;if(uc<0x80)len=1;elseif(uc<0x800)len=2;elseif(uc<0x10000)len=3;ptr2+=len; switch(len){ case4:*--ptr2=((uc|0x80)&0xBF);uc>>=6; case3:*--ptr2=((uc|0x80)&0xBF);uc>>=6; case2:*--ptr2=((uc|0x80)&0xBF);uc>>=6; case1:*--ptr2=(uc|firstByteMark[len]); } ptr2+=len; break; default:*ptr2++=*ptr;break; } ptr++; } } *ptr2=0; if(*ptr=='\"')ptr++; item->valuestring=out; item->type=cJSON_String; returnptr; } /*Renderthecstringprovidedtoanescapedversionthatcanbeprinted.*/ staticchar*print_string_ptr(constchar*str,printbuffer*p) { constchar*ptr;char*ptr2,*out;intlen=0,flag=0;unsignedchartoken; for(ptr=str;*ptr;ptr++)flag|=((*ptr>0&&*ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; if(!flag) { len=ptr-str; if(p)out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if(!out)return0; ptr2=out;*ptr2++='\"'; strcpy(ptr2,str); ptr2[len]='\"'; ptr2[len+1]=0; returnout; } if(!str) { if(p) out=ensure(p,3); else out=(char*)cJSON_malloc(3); if(!out)return0; strcpy(out,"\"\""); returnout; } ptr=str;while((token=*ptr)&&++len){if(strchr("\"\\\b\f\n\r\t",token))len++;elseif(token<32)len+=5;ptr++;} if(p) out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if(!out)return0; ptr2=out;ptr=str; *ptr2++='\"'; while(*ptr) { if((unsignedchar)*ptr>31&&*ptr!='\"'&&*ptr!='\\')*ptr2++=*ptr++; else { *ptr2++='\\'; switch(token=*ptr++) { case'\\': *ptr2++='\\'; break; case'\"': *ptr2++='\"'; break; case'\b': *ptr2++='b'; break; case'\f': *ptr2++='f'; break; case'\n': *ptr2++='n'; break; case'\r': *ptr2++='r'; break; case'\t': *ptr2++='t'; break; default:sprintf(ptr2,"u%04x",token);ptr2+=5; break; /*escapeandprint*/ } } } *ptr2++='\"';*ptr2++=0; returnout; } /*Invoteprint_string_ptr(whichisuseful)onanitem.*/ staticchar*print_string(cJSON*item,printbuffer*p) {returnprint_string_ptr(item->valuestring,p);} /*Predeclaretheseprototypes.*/ staticconstchar*parse_value(cJSON*item,constchar*value); staticchar*print_value(cJSON*item,intdepth,intfmt,printbuffer*p); staticconstchar*parse_array(cJSON*item,constchar*value); staticchar*print_array(cJSON*item,printbuffer*p); staticconstchar*parse_object(cJSON*item,constchar*value); staticchar*print_object(cJSON*item,printbuffer*p); /*Utilitytojumpwhitespaceandcr/lf*/ staticconstchar*skip(constchar*in){while(in&&*in&&(unsignedchar)*in<=32)in++;returnin;} /*Parseanobject-createanewroot,andpopulate.*/ cJSON*cJSON_ParseWithOpts(constchar*value,intrequire_null_terminated) { constchar*end=0; cJSON*c=cJSON_New_Item(); ep=0; if(!c)return0;/*memoryfail*/ end=parse_value(c,skip(value)); if(!end) {cJSON_Delete(c);return0;} /*parsefailure.episset.*/ /*ifwerequirenull-terminatedJSONwithoutappendedgarbage,skipandthencheckforanullterminator*/ if(require_null_terminated){end=skip(end);if(*end){cJSON_Delete(c);ep=end;return0;}} if(return_parse_end)*return_parse_end=end; returnc; } /*DefaultoptionsforcJSON_Parse*/ cJSON*cJSON_Parse(constchar*value){returncJSON_ParseWithOpts(value,0);} /*RenderacJSONitem/entity/structuretotext.*/ char*cJSON_Print(cJSON*item) {returnprint_value(item,1,0);} char*cJSON_PrintUnformatted(cJSON*item) {returnprint_value(item,0);} char*cJSON_PrintBuffered(cJSON*item,intfmt) { printbufferp; p.buffer=(char*)cJSON_malloc(prebuffer); p.length=prebuffer; p.offset=0; returnprint_value(item,fmt,&p); returnp.buffer; } /*Parsercore-whenencounteringtext,processappropriately.*/ staticconstchar*parse_value(cJSON*item,constchar*value) { if(!value) return0; /*Failonnull.*/ if(!strncmp(value,"null",4)) {item->type=cJSON_NULL;returnvalue+4;} if(!strncmp(value,"false",5)) {item->type=cJSON_False;returnvalue+5;} if(!strncmp(value,"true",4)) {item->type=cJSON_True;item->valueint=1; returnvalue+4;} if(*value=='\"') {returnparse_string(item,value);} if(*value=='-'||(*value>='0'&&*value<='9')) {returnparse_number(item,value);} if(*value=='[') {returnparse_array(item,value);} if(*value=='{') {returnparse_object(item,value);} ep=value;return0; /*failure.*/ } /*Renderavaluetotext.*/ staticchar*print_value(cJSON*item,printbuffer*p) { char*out=0; if(!item)return0; if(p) { switch((item->type)&255) { casecJSON_NULL: {out=ensure(p,5); if(out)strcpy(out,"null"); break;} casecJSON_False: {out=ensure(p,6); if(out)strcpy(out,"false"); break;} casecJSON_True: {out=ensure(p,"true"); break;} casecJSON_Number: out=print_number(item,p);break; casecJSON_String: out=print_string(item,p);break; casecJSON_Array: out=print_array(item,depth,p);break; casecJSON_Object: out=print_object(item,p);break; } } else { switch((item->type)&255) { casecJSON_NULL: out=cJSON_strdup("null"); break; casecJSON_False: out=cJSON_strdup("false");break; casecJSON_True: out=cJSON_strdup("true");break; casecJSON_Number: out=print_number(item,0);break; casecJSON_String: out=print_string(item,0);break; casecJSON_Array: out=print_array(item,0);break; casecJSON_Object: out=print_object(item,0);break; } } returnout; } /*Buildanarrayfrominputtext.*/ staticconstchar*parse_array(cJSON*item,constchar*value) { cJSON*child; if(*value!='[') {ep=value;return0;} /*notanarray!*/ item->type=cJSON_Array; value=skip(value+1); if(*value==']')returnvalue+1; /*emptyarray.*/ item->child=child=cJSON_New_Item(); if(!item->child)return0; /*memoryfail*/ value=skip(parse_value(child,skip(value))); /*skipanyspacing,getthevalue.*/ if(!value)return0; while(*value==',') { cJSON*new_item; if(!(new_item=cJSON_New_Item()))return0; /*memoryfail*/ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_value(child,skip(value+1))); if(!value)return0; /*memoryfail*/ } if(*value==']')returnvalue+1; /*endofarray*/ ep=value;return0; /*malformed.*/ } /*Renderanarraytotext*/ staticchar*print_array(cJSON*item,printbuffer*p) { char**entries; char*out=0,*ptr,*ret;intlen=5; cJSON*child=item->child; intnumentries=0,i=0,fail=0; size_ttmplen=0; /*Howmanyentriesinthearray?*/ while(child)numentries++,child=child->next; /*Explicitlyhandlenumentries==0*/ if(!numentries) { if(p) out=ensure(p,3); else out=(char*)cJSON_malloc(3); if(out)strcpy(out,"[]"); returnout; } if(p) { /*Composetheoutputarray.*/ i=p->offset; ptr=ensure(p,1);if(!ptr)return0; *ptr='['; p->offset++; child=item->child; while(child&&!fail) { print_value(child,depth+1,p); p->offset=update(p); if(child->next){len=fmt?2:1;ptr=ensure(p,len+1);if(!ptr)return0;*ptr++=',';if(fmt)*ptr++='';*ptr=0;p->offset+=len;} child=child->next; } ptr=ensure(p,2);if(!ptr)return0; *ptr++=']';*ptr=0; out=(p->buffer)+i; } else { /*Allocateanarraytoholdthevaluesforeach*/ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if(!entries)return0; memset(entries,numentries*sizeof(char*)); /*Retrievealltheresults:*/ child=item->child; while(child&&!fail) { ret=print_value(child,0); entries[i++]=ret; if(ret)len+=strlen(ret)+2+(fmt?1:0);elsefail=1; child=child->next; } /*Ifwedidn'tfail,trytomalloctheoutputstring*/ if(!fail) out=(char*)cJSON_malloc(len); /*Ifthatfails,wefail.*/ if(!out)fail=1; /*Handlefailure.*/ if(fail) { for(i=0;i<numentries;i++)if(entries[i])cJSON_free(entries[i]); cJSON_free(entries); return0; } /*Composetheoutputarray.*/ *out='['; ptr=out+1;*ptr=0; for(i=0;i<numentries;i++) { tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen; if(i!=numentries-1){*ptr++=',';if(fmt)*ptr++='';*ptr=0;} cJSON_free(entries[i]); } cJSON_free(entries); *ptr++=']';*ptr++=0; } returnout; } /*Buildanobjectfromthetext.*/ staticconstchar*parse_object(cJSON*item,constchar*value) { cJSON*child; if(*value!='{') {ep=value;return0;} /*notanobject!*/ item->type=cJSON_Object; value=skip(value+1); if(*value=='}')returnvalue+1; /*emptyarray.*/ item->child=child=cJSON_New_Item(); if(!item->child)return0; value=skip(parse_string(child,skip(value))); if(!value)return0; child->string=child->valuestring;child->valuestring=0; if(*value!=':'){ep=value;return0;} /*fail!*/ value=skip(parse_value(child,skip(value+1))); /*skipanyspacing,getthevalue.*/ if(!value)return0; while(*value==',') { cJSON*new_item; if(!(new_item=cJSON_New_Item())) return0;/*memoryfail*/ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_string(child,skip(value+1))); if(!value)return0; child->string=child->valuestring;child->valuestring=0; if(*value!=':'){ep=value;return0;} /*fail!*/ value=skip(parse_value(child,getthevalue.*/ if(!value)return0; } if(*value=='}')returnvalue+1; /*endofarray*/ ep=value;return0; /*malformed.*/ } /*Renderanobjecttotext.*/ staticchar*print_object(cJSON*item,printbuffer*p) { char**entries=0,**names=0; char*out=0,*ret,*str;intlen=7,j; cJSON*child=item->child; intnumentries=0,fail=0; size_ttmplen=0; /*Countthenumberofentries.*/ while(child)numentries++,child=child->next; /*Explicitlyhandleemptyobjectcase*/ if(!numentries) { if(p)out=ensure(p,fmt?depth+4:3); else out=(char*)cJSON_malloc(fmt?depth+4:3); if(!out) return0; ptr=out;*ptr++='{'; if(fmt){*ptr++='\n';for(i=0;i<depth-1;i++)*ptr++='\t';} *ptr++='}';*ptr++=0; returnout; } if(p) { /*Composetheoutput:*/ i=p->offset; len=fmt?2:1; ptr=ensure(p,len+1); if(!ptr)return0; *ptr++='{'; if(fmt)*ptr++='\n'; *ptr=0; p->offset+=len; child=item->child;depth++; while(child) { if(fmt) { ptr=ensure(p,depth); if(!ptr)return0; for(j=0;j<depth;j++)*ptr++='\t'; p->offset+=depth; } print_string_ptr(child->string,p); p->offset=update(p); len=fmt?2:1; ptr=ensure(p,len); if(!ptr)return0; *ptr++=':';if(fmt)*ptr++='\t'; p->offset+=len; print_value(child,p); p->offset=update(p); len=(fmt?1:0)+(child->next?1:0); ptr=ensure(p,len+1);if(!ptr)return0; if(child->next)*ptr++=','; if(fmt)*ptr++='\n';*ptr=0; p->offset+=len; child=child->next; } ptr=ensure(p,fmt?(depth+1):2); if(!ptr)return0; if(fmt) for(i=0;i<depth-1;i++)*ptr++='\t'; *ptr++='}';*ptr=0; out=(p->buffer)+i; } else { /*Allocatespaceforthenamesandtheobjects*/ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if(!entries)return0; names=(char**)cJSON_malloc(numentries*sizeof(char*)); if(!names){cJSON_free(entries);return0;} memset(entries,sizeof(char*)*numentries); memset(names,sizeof(char*)*numentries); /*Collectalltheresultsintoourarrays:*/ child=item->child;depth++;if(fmt)len+=depth; while(child) { names[i]=str=print_string_ptr(child->string,0); entries[i++]=ret=print_value(child,0); if(str&&ret)len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0);elsefail=1; child=child->next; } /*Trytoallocatetheoutputstring*/ if(!fail) out=(char*)cJSON_malloc(len); if(!out)fail=1; /*Handlefailure*/ if(fail) { for(i=0;i<numentries;i++){if(names[i])cJSON_free(names[i]);if(entries[i])cJSON_free(entries[i]);} cJSON_free(names);cJSON_free(entries); return0; } /*Composetheoutput:*/ *out='{';ptr=out+1;if(fmt)*ptr++='\n';*ptr=0; for(i=0;i<numentries;i++) { if(fmt)for(j=0;j<depth;j++)*ptr++='\t'; tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen; *ptr++=':';if(fmt)*ptr++='\t'; strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if(i!=numentries-1)*ptr++=','; if(fmt)*ptr++='\n';*ptr=0; cJSON_free(names[i]);cJSON_free(entries[i]); } cJSON_free(names);cJSON_free(entries); if(fmt)for(i=0;i<depth-1;i++)*ptr++='\t'; *ptr++='}';*ptr++=0; } returnout; } /*GetArraysize/item/objectitem.*/ intcJSON_GetArraySize(cJSON*array) {cJSON*c=array->child;inti=0;while(c)i++,c=c->next;returni;} cJSON*cJSON_GetArrayItem(cJSON*array,intitem) {cJSON*c=array->child;while(c&&item>0)item--,c=c->next;returnc;} cJSON*cJSON_GetObjectItem(cJSON*object,constchar*string) {cJSON*c=object->child;while(c&&cJSON_strcasecmp(c->string,string))c=c->next;returnc;} /*Utilityforarraylisthandling.*/ staticvoidsuffix_object(cJSON*prev,cJSON*item){prev->next=item;item->prev=prev;} /*Utilityforhandlingreferences.*/ staticcJSON*create_reference(cJSON*item){cJSON*ref=cJSON_New_Item();if(!ref)return0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;returnref;} /*Additemtoarray/object.*/ voidcJSON_AddItemToArray(cJSON*array,cJSON*item) {cJSON*c=array->child;if(!item)return;if(!c){array->child=item;}else{while(c&&c->next)c=c->next;suffix_object(c,item);}} voidcJSON_AddItemToObject(cJSON*object,cJSON*item) {if(!item)return;if(item->string)cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} voidcJSON_AddItemToObjectCS(cJSON*object,cJSON*item) {if(!item)return;if(!(item->type&cJSON_StringIsConst)&&item->string)cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);} void cJSON_AddItemReferenceToArray(cJSON*array,cJSON*item) {cJSON_AddItemToArray(array,create_reference(item));} void cJSON_AddItemReferenceToObject(cJSON*object,cJSON*item) {cJSON_AddItemToObject(object,string,create_reference(item));} cJSON*cJSON_DetachItemFromArray(cJSON*array,intwhich) {cJSON*c=array->child;while(c&&which>0)c=c->next,which--;if(!c)return0; if(c->prev)c->prev->next=c->next;if(c->next)c->next->prev=c->prev;if(c==array->child)array->child=c->next;c->prev=c->next=0;returnc;} voidcJSON_DeleteItemFromArray(cJSON*array,intwhich) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} cJSON*cJSON_DetachItemFromObject(cJSON*object,constchar*string){inti=0;cJSON*c=object->child;while(c&&cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c)returncJSON_DetachItemFromArray(object,i);return0;} voidcJSON_DeleteItemFromObject(cJSON*object,constchar*string){cJSON_Delete(cJSON_DetachItemFromObject(object,string));} /*Replacearray/objectitemswithnewones.*/ voidcJSON_InsertItemInArray(cJSON*array,cJSON*newitem) {cJSON*c=array->child;while(c&&which>0)c=c->next,which--;if(!c){cJSON_AddItemToArray(array,newitem);return;} newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if(c==array->child)array->child=newitem;elsenewitem->prev->next=newitem;} voidcJSON_ReplaceItemInArray(cJSON*array,which--;if(!c)return; newitem->next=c->next;newitem->prev=c->prev;if(newitem->next)newitem->next->prev=newitem; if(c==array->child)array->child=newitem;elsenewitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} voidcJSON_ReplaceItemInObject(cJSON*object,cJSON*newitem){inti=0;cJSON*c=object->child;while(c&&cJSON_strcasecmp(c->string,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} /*Createbasictypes:*/ cJSON*cJSON_CreateNull(void) {cJSON*item=cJSON_New_Item();if(item)item->type=cJSON_NULL;returnitem;} cJSON*cJSON_CreateTrue(void) {cJSON*item=cJSON_New_Item();if(item)item->type=cJSON_True;returnitem;} cJSON*cJSON_CreateFalse(void) {cJSON*item=cJSON_New_Item();if(item)item->type=cJSON_False;returnitem;} cJSON*cJSON_CreateBool(intb) {cJSON*item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;returnitem;} cJSON*cJSON_CreateNumber(doublenum) {cJSON*item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}returnitem;} cJSON*cJSON_CreateString(constchar*string) {cJSON*item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}returnitem;} cJSON*cJSON_CreateArray(void) {cJSON*item=cJSON_New_Item();if(item)item->type=cJSON_Array;returnitem;} cJSON*cJSON_CreateObject(void) {cJSON*item=cJSON_New_Item();if(item)item->type=cJSON_Object;returnitem;} /*CreateArrays:*/ cJSON*cJSON_CreateIntArray(constint*numbers,intcount) {inti;cJSON*n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a&&i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;elsesuffix_object(p,n);p=n;}returna;} cJSON*cJSON_CreateFloatArray(constfloat*numbers,intcount) {inti;cJSON*n=0,n);p=n;}returna;} cJSON*cJSON_CreateDoubleArray(constdouble*numbers,n);p=n;}returna;} cJSON*cJSON_CreateStringArray(constchar**strings,*a=cJSON_CreateArray();for(i=0;a&&i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;elsesuffix_object(p,n);p=n;}returna;} /*Duplication*/ cJSON*cJSON_Duplicate(cJSON*item,intrecurse) { cJSON*newitem,*cptr,*nptr=0,*newchild; /*Bailonbadptr*/ if(!item)return0; /*Createnewitem*/ newitem=cJSON_New_Item(); if(!newitem)return0; /*Copyoverallvars*/ newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; if(item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if(!newitem->valuestring) {cJSON_Delete(newitem);return0;}} if(item->string) {newitem->string=cJSON_strdup(item->string); if(!newitem->string) {cJSON_Delete(newitem);return0;}} /*Ifnon-recursive,thenwe'redone!*/ if(!recurse)returnnewitem; /*Walkthe->nextchainforthechild.*/ cptr=item->child; while(cptr) { newchild=cJSON_Duplicate(cptr,1); /*Duplicate(withrecurse)eachiteminthe->nextchain*/ if(!newchild){cJSON_Delete(newitem);return0;} if(nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /*Ifnewitem->childalreadyset,thencrosswire->prevand->nextandmoveon*/ else {newitem->child=newchild;nptr=newchild;} /*Setnewitem->childandmovetoit*/ cptr=cptr->next; } returnnewitem; } voidcJSON_Minify(char*json) { char*into=json; while(*json) { if(*json=='')json++; elseif(*json=='\t')json++; /*Whitespacecharacters.*/ elseif(*json=='\r')json++; elseif(*json=='\n')json++; elseif(*json=='/'&&json[1]=='/')while(*json&&*json!='\n')json++; /*double-slashcomments,toendofline.*/ elseif(*json=='/'&&json[1]=='*'){while(*json&&!(*json=='*'&&json[1]=='/'))json++;json+=2;} /*multilinecomments.*/ elseif(*json=='\"'){*into++=*json++;while(*json&&*json!='\"'){if(*json=='\\')*into++=*json++;*into++=*json++;}*into++=*json++;}/*stringliterals,whichare\"sensitive.*/ else*into++=*json++; /*Allothercharacters.*/ } *into=0; /*andnull-terminate.*/ } chunli@Linux:~/ace/json/cJSON$
测试程序:
chunli@Linux:~/ace/json/cJSON$catmain.c /* Copyright(c)2009DaveGamble Permissionisherebygranted,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN THESOFTWARE. */ #include<stdio.h> #include<stdlib.h> #include"cJSON.h" /*ParsetexttoJSON,thenrenderbacktotext,andprint!*/ voiddoit(char*text) { char*out;cJSON*json; json=cJSON_Parse(text); if(!json){printf("Errorbefore:[%s]\n",cJSON_GetErrorPtr());} else { out=cJSON_Print(json); cJSON_Delete(json); printf("%s\n",out); free(out); } } /*Readafile,parse,renderback,etc.*/ voiddofile(char*filename) { FILE*f;longlen;char*data; f=fopen(filename,"rb");fseek(f,SEEK_END);len=ftell(f);fseek(f,SEEK_SET); data=(char*)malloc(len+1);fread(data,len,f);fclose(f); doit(data); free(data); } /*Usedbysomecodebelowasanexampledatatype.*/ structrecord{constchar*precision;doublelat,lon;constchar*address,*city,*state,*zip,*country;}; /*Createabunchofobjectsasdemonstration.*/ voidcreate_objects() { cJSON*root,*fmt,*img,*thm,*fld;char*out;inti; /*declareafew.*/ /*Our"daysoftheweek"array:*/ constchar*strings[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; /*Ourmatrix:*/ intnumbers[3][3]={{0,-1,0},{1,{0,1}}; /*Our"gallery"item:*/ intids[4]={116,943,234,38793}; /*Ourarrayof"records":*/ structrecordfields[2]={ {"zip",37.7668,-1.223959e+2,"","SANFRANCISCO","CA","94107","US"},{"zip",37.371991,-1.22026e+2,"SUNNYVALE","94085","US"}}; /*HereweconstructsomeJSONstandards,fromtheJSONsite.*/ /*Our"Video"datatype:*/ 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,"framerate",24); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /*Printtotext,DeletethecJSON,printit,releasethestring.*/ /*Our"daysoftheweek"array:*/ root=cJSON_CreateStringArray(strings,7); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /*Ourmatrix:*/ root=cJSON_CreateArray(); for(i=0;i<3;i++)cJSON_AddItemToArray(root,cJSON_CreateIntArray(numbers[i],3)); /* cJSON_ReplaceItemInArray(root,cJSON_CreateString("Replacement"));*/ out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /*Our"gallery"item:*/ root=cJSON_CreateObject(); cJSON_AddItemToObject(root,"Image",img=cJSON_CreateObject()); cJSON_AddNumberToObject(img,"Width",800); cJSON_AddNumberToObject(img,"Height",600); cJSON_AddStringToObject(img,"Title","Viewfrom15thFloor"); cJSON_AddItemToObject(img,"Thumbnail",thm=cJSON_CreateObject()); cJSON_AddStringToObject(thm,"Url","http:/*www.example.com/image/481989943"); cJSON_AddNumberToObject(thm,125); cJSON_AddStringToObject(thm,"100"); cJSON_AddItemToObject(img,"IDs",cJSON_CreateIntArray(ids,4)); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /*Ourarrayof"records":*/ 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),4));*/ out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); } intmain(intargc,constchar*argv[]){ /*abunchofjson:*/ chartext1[]="{\n\"name\":\"Jack(\\\"Bee\\\")Nimble\",\n\"format\":{\"type\":\"rect\",\n\"width\":1920,\n\"height\":1080,\n\"interlace\":false,\"framerate\":24\n}\n}"; chartext2[]="[\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"]"; chartext3[]="[\n[0,0],\n[1,\n[0,1]\n ]\n"; chartext4[]="{\n \"Image\":{\n \"Width\":800,\n \"Height\":600,\n \"Title\":\"Viewfrom15thFloor\",\n \"Thumbnail\":{\n \"Url\":\"http:/*www.example.com/image/481989943\",\n \"Height\":125,\n \"Width\":\"100\"\n },\n \"IDs\":[116,38793]\n }\n }"; chartext5[]="[\n {\n \"precision\":\"zip\",\n \"Latitude\":37.7668,\n \"Longitude\":-122.3959,\n \"Address\":\"\",\n \"City\":\"SANFRANCISCO\",\n \"State\":\"CA\",\n \"Zip\":\"94107\",\n \"Country\":\"US\"\n },\n {\n \"precision\":\"zip\",\n \"Latitude\":37.371991,\n \"Longitude\":-122.026020,\n \"City\":\"SUNNYVALE\",\n \"Zip\":\"94085\",\n \"Country\":\"US\"\n }\n ]"; inti=0; /*Processeachjsontextblockbyparsing,thenrebuilding:*/ printf("%d-----------------------------------------\n",++i); doit(text1); printf("%d-----------------------------------------\n",++i); doit(text2); printf("%d-----------------------------------------\n",++i); doit(text3);printf("%d-----------------------------------------\n",++i); doit(text4);printf("%d-----------------------------------------\n",++i); doit(text5);printf("%d-----------------------------------------\n",++i); /*Parsestandardtestfiles:*/ dofile("./tests/test1");printf("%d-----------------------------------------\n",++i); dofile("./tests/test2");printf("%d-----------------------------------------\n",++i); dofile("./tests/test3");printf("%d-----------------------------------------\n",++i); dofile("./tests/test4");printf("%d-----------------------------------------\n",++i); dofile("./tests/test5");printf("%d-----------------------------------------\n",++i); /*Nowsomesamplecodeforbuildingobjectsconcisely:*/ create_objects(); return0; } chunli@Linux:~/ace/json/cJSON$
测试所用的json文本
chunli@Linux:~/ace/json/cJSON$cattests/test1 { "glossary":{ "title":"exampleglossary","GlossDiv":{ "title":"S","GlossList":{ "GlossEntry":{ "ID":"SGML","SortAs":"SGML","GlossTerm":"StandardGeneralizedMarkupLanguage","Acronym":"SGML","Abbrev":"ISO8879:1986","GlossDef":{ "para":"AMeta-markuplanguage,usedtocreatemarkuplanguagessuchasDocBook.","GlossSeeAlso":["GML","XML"] },"GlossSee":"markup" } } } } } chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$cattests/test2 {"menu":{ "id":"file","value":"File","popup":{ "menuitem":[ {"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"} ] } }} chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$cattests/test3 {"widget":{ "debug":"on","window":{ "title":"SampleKonfabulatorWidget","name":"main_window","width":500,"height":500 },"image":{ "src":"Images/Sun.png","name":"sun1","hOffset":250,"vOffset":250,"alignment":"center" },"text":{ "data":"ClickHere","size":36,"style":"bold","name":"text1","vOffset":100,"alignment":"center","onMouseUp":"sun1.opacity=(sun1.opacity/100)*90;" } }}chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$cattests/test4 {"web-app":{ "servlet":[ { "servlet-name":"cofaxCDS","servlet-class":"org.cofax.cds.CDSServlet","init-param":{ "configGlossary:installationAt":"Philadelphia,PA","configGlossary:adminEmail":"ksm@poBox.com","configGlossary:poweredBy":"Cofax","configGlossary:poweredByIcon":"/images/cofax.gif","configGlossary:staticPath":"/content/static","templateProcessorClass":"org.cofax.WysiwygTemplate","templateLoaderClass":"org.cofax.FilesTemplateLoader","templatePath":"templates","templateOverridePath":"","defaultListTemplate":"listTemplate.htm","defaultFileTemplate":"articleTemplate.htm","useJSP":false,"jspListTemplate":"listTemplate.jsp","jspFileTemplate":"articleTemplate.jsp","cachePackageTagsTrack":200,"cachePackageTagsStore":200,"cachePackageTagsRefresh":60,"cacheTemplatesTrack":100,"cacheTemplatesStore":50,"cacheTemplatesRefresh":15,"cachePagesTrack":200,"cachePagesStore":100,"cachePagesRefresh":10,"cachePagesDirtyRead":10,"searchEngineListTemplate":"forSearchEnginesList.htm","searchEngineFileTemplate":"forSearchEngines.htm","searchEngineRobotsDb":"WEB-INF/robots.db","useDataStore":true,"dataStoreClass":"org.cofax.sqlDataStore","redirectionClass":"org.cofax.sqlRedirection","dataStoreName":"cofax","dataStoreDriver":"com.microsoft.jdbc.sqlserver.sqlServerDriver","dataStoreUrl":"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon","dataStoreUser":"sa","dataStorePassword":"dataStoreTestQuery","dataStoreTestQuery":"SETNOCOUNTON;selecttest='test';","dataStoreLogFile":"/usr/local/tomcat/logs/datastore.log","dataStoreInitConns":10,"dataStoreMaxConns":100,"dataStoreConnUsageLimit":100,"dataStoreLogLevel":"debug","maxUrlLength":500}},{ "servlet-name":"cofaxEmail","servlet-class":"org.cofax.cds.EmailServlet","init-param":{ "mailHost":"mail1","mailHostOverride":"mail2"}},{ "servlet-name":"cofaxAdmin","servlet-class":"org.cofax.cds.AdminServlet"},{ "servlet-name":"fileServlet","servlet-class":"org.cofax.cds.FileServlet"},{ "servlet-name":"cofaxTools","servlet-class":"org.cofax.cms.CofaxToolsServlet","init-param":{ "templatePath":"toolstemplates/","log":1,"logLocation":"/usr/local/tomcat/logs/CofaxTools.log","logMaxSize":"","dataLog":1,"dataLogLocation":"/usr/local/tomcat/logs/dataLog.log","dataLogMaxSize":"","removePageCache":"/content/admin/remove?cache=pages&id=","removeTemplateCache":"/content/admin/remove?cache=templates&id=","fileTransferFolder":"/usr/local/tomcat/webapps/content/fileTransferFolder","lookInContext":1,"adminGroupID":4,"betaServer":true}}],"servlet-mapping":{ "cofaxCDS":"/","cofaxEmail":"/cofaxutil/aemail/*","cofaxAdmin":"/admin/*","fileServlet":"/static/*","cofaxTools":"/tools/*"},"taglib":{ "taglib-uri":"cofax.tld","taglib-location":"/WEB-INF/tlds/cofax.tld"}}}chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$cattests/test5 {"menu":{ "header":"SVGViewer","items":[ {"id":"Open"},{"id":"OpenNew","label":"OpenNew"},null,{"id":"ZoomIn","label":"ZoomIn"},{"id":"ZoomOut","label":"ZoomOut"},{"id":"OriginalView","label":"OriginalView"},{"id":"Quality"},{"id":"Pause"},{"id":"Mute"},{"id":"Find","label":"Find..."},{"id":"FindAgain","label":"FindAgain"},{"id":"Copy"},{"id":"CopyAgain","label":"CopyAgain"},{"id":"CopySVG","label":"CopySVG"},{"id":"ViewSVG","label":"ViewSVG"},{"id":"ViewSource","label":"ViewSource"},{"id":"SaveAs","label":"SaveAs"},{"id":"Help"},{"id":"About","label":"AboutAdobeCVGViewer..."} ] }} chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$
编译运行:
chunli@Linux:~/ace/json/cJSON$ chunli@Linux:~/ace/json/cJSON$gccmain.ccJSON.c-lm&&./a.out 1----------------------------------------- { "name": "Jack(\"Bee\")Nimble","format": { "type": "rect","width": 1920,"height": 1080,"interlace": false,"framerate": 24 } } 2----------------------------------------- ["Sunday","Saturday"] 3----------------------------------------- [[0,[1,[0,1]] 4----------------------------------------- { "Image": { "Width": 800,"Height": 600,"Title": "Viewfrom15thFloor","Thumbnail": { "Url": "http:/*www.example.com/image/481989943","Height": 125,"Width": "100" },"IDs": [116,38793] } } 5----------------------------------------- [{ "precision": "zip","Latitude": 37.766800,"Longitude": -122.395900,"Address": "","City": "SANFRANCISCO","State": "CA","Zip": "94107","Country": "US" },{ "precision": "zip","Latitude": 37.371991,"Longitude": -122.026020,"City": "SUNNYVALE","Zip": "94085","Country": "US" }] 6----------------------------------------- { "glossary": { "title": "exampleglossary","GlossDiv": { "title": "S","GlossList": { "GlossEntry": { "ID": "SGML","SortAs": "SGML","GlossTerm": "StandardGeneralizedMarkupLanguage","Acronym": "SGML","Abbrev": "ISO8879:1986","GlossDef": { "para": "AMeta-markuplanguage,"GlossSeeAlso": ["GML","XML"] },"GlossSee": "markup" } } } } } 7----------------------------------------- { "menu": { "id": "file","value": "File","popup": { "menuitem": [{ "value": "New","onclick": "CreateNewDoc()" },{ "value": "Open","onclick": "OpenDoc()" },{ "value": "Close","onclick": "CloseDoc()" }] } } } 8----------------------------------------- { "widget": { "debug": "on","window": { "title": "SampleKonfabulatorWidget","name": "main_window","width": 500,"height": 500 },"image": { "src": "Images/Sun.png","name": "sun1","hOffset": 250,"vOffset": 250,"alignment": "center" },"text": { "data": "ClickHere","size": 36,"style": "bold","name": "text1","vOffset": 100,"alignment": "center","onMouseUp": "sun1.opacity=(sun1.opacity/100)*90;" } } } 9----------------------------------------- { "web-app": { "servlet": [{ "servlet-name": "cofaxCDS","servlet-class": "org.cofax.cds.CDSServlet","init-param": { "configGlossary:installationAt": "Philadelphia,"configGlossary:adminEmail": "ksm@poBox.com","configGlossary:poweredBy": "Cofax","configGlossary:poweredByIcon": "/images/cofax.gif","configGlossary:staticPath": "/content/static","templateProcessorClass": "org.cofax.WysiwygTemplate","templateLoaderClass": "org.cofax.FilesTemplateLoader","templatePath": "templates","templateOverridePath": "","defaultListTemplate": "listTemplate.htm","defaultFileTemplate": "articleTemplate.htm","useJSP": false,"jspListTemplate": "listTemplate.jsp","jspFileTemplate": "articleTemplate.jsp","cachePackageTagsTrack": 200,"cachePackageTagsStore": 200,"cachePackageTagsRefresh": 60,"cacheTemplatesTrack": 100,"cacheTemplatesStore": 50,"cacheTemplatesRefresh": 15,"cachePagesTrack": 200,"cachePagesStore": 100,"cachePagesRefresh": 10,"cachePagesDirtyRead": 10,"searchEngineListTemplate": "forSearchEnginesList.htm","searchEngineFileTemplate": "forSearchEngines.htm","searchEngineRobotsDb": "WEB-INF/robots.db","useDataStore": true,"dataStoreClass": "org.cofax.sqlDataStore","redirectionClass": "org.cofax.sqlRedirection","dataStoreName": "cofax","dataStoreDriver": "com.microsoft.jdbc.sqlserver.sqlServerDriver","dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon","dataStoreUser": "sa","dataStorePassword": "dataStoreTestQuery","dataStoreTestQuery": "SETNOCOUNTON;selecttest='test';","dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log","dataStoreInitConns": 10,"dataStoreMaxConns": 100,"dataStoreConnUsageLimit": 100,"dataStoreLogLevel": "debug","maxUrlLength": 500 } },{ "servlet-name": "cofaxEmail","servlet-class": "org.cofax.cds.EmailServlet","init-param": { "mailHost": "mail1","mailHostOverride": "mail2" } },{ "servlet-name": "cofaxAdmin","servlet-class": "org.cofax.cds.AdminServlet" },{ "servlet-name": "fileServlet","servlet-class": "org.cofax.cds.FileServlet" },{ "servlet-name": "cofaxTools","servlet-class": "org.cofax.cms.CofaxToolsServlet","init-param": { "templatePath": "toolstemplates/","log": 1,"logLocation": "/usr/local/tomcat/logs/CofaxTools.log","logMaxSize": "","dataLog": 1,"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log","dataLogMaxSize": "","removePageCache": "/content/admin/remove?cache=pages&id=","removeTemplateCache": "/content/admin/remove?cache=templates&id=","fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder","lookInContext": 1,"adminGroupID": 4,"betaServer": true } }],"servlet-mapping": { "cofaxCDS": "/","cofaxEmail": "/cofaxutil/aemail/*","cofaxAdmin": "/admin/*","fileServlet": "/static/*","cofaxTools": "/tools/*" },"taglib": { "taglib-uri": "cofax.tld","taglib-location": "/WEB-INF/tlds/cofax.tld" } } } 10----------------------------------------- { "menu": { "header": "SVGViewer","items": [{ "id": "Open" },{ "id": "OpenNew","label": "OpenNew" },{ "id": "ZoomIn","label": "ZoomIn" },{ "id": "ZoomOut","label": "ZoomOut" },{ "id": "OriginalView","label": "OriginalView" },{ "id": "Quality" },{ "id": "Pause" },{ "id": "Mute" },{ "id": "Find","label": "Find..." },{ "id": "FindAgain","label": "FindAgain" },{ "id": "Copy" },{ "id": "CopyAgain","label": "CopyAgain" },{ "id": "CopySVG","label": "CopySVG" },{ "id": "ViewSVG","label": "ViewSVG" },{ "id": "ViewSource","label": "ViewSource" },{ "id": "SaveAs","label": "SaveAs" },{ "id": "Help" },{ "id": "About","label": "AboutAdobeCVGViewer..." }] } } 11----------------------------------------- { "name": "Jack(\"Bee\")Nimble","framerate": 24 } } ["Sunday","Saturday"] [[0,1]] { "Image": { "Width": 800,38793] } } [{ "precision": "zip","Longitude": -122.026000,"Country": "US" }] chunli@Linux:~/ace/json/cJSON$原文链接:https://www.f2er.com/json/289053.html