JSON-03 cJSON的安装、使用 以及 官方的Demo案例



cJSON的使用

1. 介绍

cJSON 库是C语言中的最常用的 JSON 库
https://github.com/DaveGamble/cJSON
https://sourceforge.net/projects/cjson/


1.1 不安装,直接使用cJSON源码

从GitHub拉取cJSON源码

git clone https://github.com/DaveGamble/cJSON.git

文件非常多,但cJSON的源码文件只有两个:

cJSON.h
cJSON.c

使用的时候,只需要将这两个文件复制到工程目录,然后包含头文件cJSON.h即可,如下:

#include "cJSON.h"

1.2 安装cJSON到Linux

如果不想每次拷贝cJSON的源文件到项目中,可以安装一下;

git clone https://github.com/DaveGamble/cJSON.git
cd cJSON/
make all
make install

实际操作如下:

[root@lwh ~]# git clone https://github.com/DaveGamble/cJSON.git
Cloning into 'cJSON'...
remote: Enumerating objects: 4470, done.
remote: Total 4470 (delta 0), reused 0 (delta 0), pack-reused 4470
Receiving objects: 100% (4470/4470), 2.41 MiB | 9.00 KiB/s, done.
Resolving deltas: 100% (2976/2976), done.

[root@lwh ~]# cd cJSON/


[root@lwh cJSON]# ls
appveyor.yml  CHANGELOG.md  cJSON.h        cJSON_Utils.h   CONTRIBUTORS.md  library_config  Makefile   test.c  valgrind.supp
build         cJSON.c       cJSON_Utils.c  CMakeLists.txt  fuzzing          LICENSE         README.md  tests

[root@lwh cJSON]# make all
gcc -std=c89 -c -fPIC -pedantic -Wall -Werror -Wstrict-prototypes -Wwrite-strings -Wshadow -Winit-self -Wcast-align -Wformat=2 -Wmissing-prototypes -Wstrict-overflow=2 -Wcast-qual -Wc++-compat -Wundef -Wswitch-default -Wconversion -fstack-protector cJSON.c
gcc -std=c89 -shared -o libcjson.so.1.7.14 cJSON.o -Wl,-soname=libcjson.so.1 
ln -s libcjson.so.1.7.14 libcjson.so.1
ln -s libcjson.so.1 libcjson.so
gcc -std=c89 -c -fPIC -pedantic -Wall -Werror -Wstrict-prototypes -Wwrite-strings -Wshadow -Winit-self -Wcast-align -Wformat=2 -Wmissing-prototypes -Wstrict-overflow=2 -Wcast-qual -Wc++-compat -Wundef -Wswitch-default -Wconversion -fstack-protector cJSON_Utils.c
gcc -std=c89 -shared -o libcjson_utils.so.1.7.14 cJSON_Utils.o cJSON.o -Wl,-soname=libcjson_utils.so.1 
ln -s libcjson_utils.so.1.7.14 libcjson_utils.so.1
ln -s libcjson_utils.so.1 libcjson_utils.so
ar rcs libcjson.a cJSON.o
ar rcs libcjson_utils.a cJSON_Utils.o
gcc -std=c89 -fPIC -pedantic -Wall -Werror -Wstrict-prototypes -Wwrite-strings -Wshadow -Winit-self -Wcast-align -Wformat=2 -Wmissing-prototypes -Wstrict-overflow=2 -Wcast-qual -Wc++-compat -Wundef -Wswitch-default -Wconversion -fstack-protector cJSON.c test.c  -o cJSON_test -lm -I.

[root@lwh cJSON]# ls
appveyor.yml  cJSON.c  cJSON_test     cJSON_Utils.o    fuzzing      libcjson.so.1       libcjson_utils.so         library_config  README.md  valgrind.supp
build         cJSON.h  cJSON_Utils.c  CMakeLists.txt   libcjson.a   libcjson.so.1.7.14  libcjson_utils.so.1       LICENSE         test.c
CHANGELOG.md  cJSON.o  cJSON_Utils.h  CONTRIBUTORS.md  libcjson.so  libcjson_utils.a    libcjson_utils.so.1.7.14  Makefile        tests

[root@lwh cJSON]# make install
mkdir -p /usr/local/lib /usr/local/include/cjson
cp -a cJSON.h /usr/local/include/cjson
cp -a libcjson.so libcjson.so.1 libcjson.so.1.7.14 /usr/local/lib
cp -a cJSON_Utils.h /usr/local/include/cjson
cp -a libcjson_utils.so libcjson_utils.so.1 libcjson_utils.so.1.7.14 /usr/local/lib

会生成动态库 并把
头文件cJSON.h 拷贝到 /usr/local/include/cjson 目录下,
库文件libcjson.so 拷贝到 /usr/local/lib 目录下 。

安装完成后,需要将 /usr/local/lib 添加到 /etc/ld.so.conf 文件中,然后执行 ldconfig;
否则程序在运行时会报 error while loading shared libraries: libcjson.so.1: cannot open shared object file: No such file or directory

使用的时候

#include <cjson/cJSON.h>
gcc testcjson.c -o testcjson -lcjson
gcc testcjson.c -o testcjson -lcjson -L/usr/local/lib -I/usr/local/include/cjson 

2. cJSON demo

cJSON官方GitHub的例子

经过改写后如下所示:

2.1 testcjson.cjson

{
    "name": "Awesome 4K",
    "resolutions": [
        {
            "width": 1280,
            "height": 720
        },
        {
            "width": 1920,
            "height": 1080
        },
        {
            "width": 3840,
            "height": 2160
        }
    ]
}

2.2 testcjson.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <cjson/cJSON.h>

#define Print_FuncLine printf("\n%s %d\n", __func__, __LINE__);

//解析JSON
void parse_json(const char *filename)
{
    printf("----------------parse json start-------------------------------\n");

    //从文件中读取要解析的JSON数据
    FILE *fp = fopen(filename, "r");

    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    char *data = (char *)malloc(len + 1);

    fseek(fp, 0, SEEK_SET);
    fread(data, 1, len, fp);

    fclose(fp);

    printf("%s", data); //打印读到的字符串

    //将字符串解析成json结构体
    cJSON *monitor_json = cJSON_Parse(data);
    if (NULL == monitor_json)
    {
        printf("error:%s\n", cJSON_GetErrorPtr());
    }

    cJSON *name_json = cJSON_GetObjectItemCaseSensitive(monitor_json, "name");
    if (name_json != NULL)
    {
        printf("%s\n", name_json->valuestring);
    }

    cJSON *resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");
    if (resolutions == NULL)
    {
        printf("error:%s\n", cJSON_GetErrorPtr());
    }

    //数组中包含3个对象,获取对象的个数(数组元素的个数)
    int arraySize = cJSON_GetArraySize(resolutions);
    printf("array size is %d\n", arraySize);

    cJSON *resolution = NULL;
    cJSON *wild = NULL;
    cJSON *height = NULL;

    for (int i = 0; i < arraySize; ++i) //数组中包含3个对象
    {
        resolution = cJSON_GetArrayItem(resolutions, i);
        if (resolution != NULL)
        {
            //Print_FuncLine;
            wild = cJSON_GetObjectItem(resolution, "width");
            printf("width: %d\n", wild->valueint);
            height = cJSON_GetObjectItem(resolution, "height");
            printf("height: %d\n", height->valueint);
        }
        else
        {
            //Print_FuncLine;
            printf("error:%s\n", cJSON_GetErrorPtr());
        }
    }
    cJSON_Delete(monitor_json);
    free(data);
    printf("----------------parse json end--------------------------------\n\n");
}
//创建JSON
void create_json()
{
    printf("----------------create json start-----------------------------\n");
    size_t index = 0;
    const unsigned int resolution_numbers[3][2] = {{1280, 720}, {1920, 1080}, {3840, 2160}};

    //最外层的json对象
    cJSON *monitor_json = cJSON_CreateObject();

    //添加第1个键值对
    cJSON_AddItemToObject(monitor_json, "name", cJSON_CreateString("Awesome 4K"));

    //添加第2个键值对;第二个键值对是一个数组,数组中是3个json对象
    cJSON *resolutions = cJSON_CreateArray();
    cJSON_AddItemToObject(monitor_json, "resolutions", resolutions);

    //向第二个键值对中添加3个json对象
    /*C语言如何求二维数组行数和列数
        比如有这样一个二维数组: int a[3][5];
        求数组元素的总数: sizeof(a) / sizeof(int)
        求数组列数: sizeof(a[0])/sizeof(int)
        而数组行数则为 :( sizeof(a) / sizeof(int) )/ ( sizeof(a[0]) / sizeof(int) )
    */
    int array_len = (sizeof(resolution_numbers) / sizeof(resolution_numbers[0][0])) /
                    (sizeof(resolution_numbers[0]) / sizeof(resolution_numbers[0][0]));
    for (int index = 0; index < array_len; ++index)
    {
        cJSON *resolution = cJSON_CreateObject();
        cJSON_AddItemToArray(resolutions, resolution);

        cJSON_AddNumberToObject(resolution, "wild", resolution_numbers[index][0]);
        cJSON_AddNumberToObject(resolution, "hight", resolution_numbers[index][1]);
    }

    //打印JSON
    char *text = cJSON_Print(monitor_json); // cJSON_Print会malloc申请内存,text要free掉
    printf("%s\n", text);
    free(text);
    cJSON_Delete(monitor_json);
    printf("----------------create json end-------------------------------\n\n");
}
int main()
{
    parse_json("testcjson.txt");
    create_json();
    return 0;
}
注意释放内存:

cJSON_Print会malloc申请内存,text要free掉

打印JSON
	cJSON_Print会malloc申请内存,text要free掉 
    char *text = cJSON_Print(monitor_json); 
    printf("%s\n", text);
    free(text);

2.3 编译运行

2.3.1 编译
[root@lwh testcpp]# gcc testcjson.c -o testcjson -lcjson -std=c99
2.3.2 运行结果如下:
[root@lwh testcpp]# ./testcjson 
----------------parse json start-------------------------------
{
    "name": "Awesome 4K",
    "resolutions": [
        {
            "width": 1280,
            "height": 720
        },
        {
            "width": 1920,
            "height": 1080
        },
        {
            "width": 3840,
            "height": 2160
        }
    ]
}
Awesome 4K
array size is 3
width: 1280
height: 720
width: 1920
height: 1080
width: 3840
height: 2160
----------------parse json end--------------------------------

----------------create json start-----------------------------
{
        "name": "Awesome 4K",
        "resolutions":  [{
                        "wild": 1280,
                        "hight":        720
                }, {
                        "wild": 1920,
                        "hight":        1080
                }, {
                        "wild": 3840,
                        "hight":        2160
                }]
}
----------------create json end-------------------------------

2.3.3 检测是否有内存泄漏
[root@lwh testcpp]# valgrind --leak-check=full ./testcjson
==20392== Memcheck, a memory error detector
==20392== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==20392== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==20392== Command: ./testcjson
==20392== 
----------------parse json start-------------------------------
==20392== Conditional jump or move depends on uninitialised value(s)
==20392==    at 0x508E029: vfprintf (in /usr/lib64/libc-2.17.so)
==20392==    by 0x5094458: printf (in /usr/lib64/libc-2.17.so)
==20392==    by 0x400DA2: parse_json (in /root/testcpp/testcjson)
==20392==    by 0x4010C9: main (in /root/testcpp/testcjson)
==20392== 
{
    "name": "Awesome 4K",
    "resolutions": [
        {
            "width": 1280,
            "height": 720
        },
        {
            "width": 1920,
            "height": 1080
        },
        {
            "width": 3840,
            "height": 2160
        }
    ]
}
==20392== Conditional jump or move depends on uninitialised value(s)
==20392==    at 0x4C2D108: strlen (vg_replace_strmem.c:461)
==20392==    by 0x4E3A74F: cJSON_ParseWithOpts (in /usr/local/lib/libcjson.so.1.7.14)
==20392==    by 0x4E3A951: cJSON_Parse (in /usr/local/lib/libcjson.so.1.7.14)
==20392==    by 0x400DAE: parse_json (in /root/testcpp/testcjson)
==20392==    by 0x4010C9: main (in /root/testcpp/testcjson)
==20392== 
Awesome 4K
array size is 3
width: 1280
height: 720
width: 1920
height: 1080
width: 3840
height: 2160
----------------parse json end--------------------------------

----------------create json start-----------------------------
{
        "name": "Awesome 4K",
        "resolutions":  [{
                        "wild": 1280,
                        "hight":        720
                }, {
                        "wild": 1920,
                        "hight":        1080
                }, {
                        "wild": 3840,
                        "hight":        2160
                }]
}
----------------create json end-------------------------------

==20392== 
==20392== HEAP SUMMARY:
==20392==     in use at exit: 0 bytes in 0 blocks
==20392==   total heap usage: 46 allocs, 46 frees, 2,944 bytes allocated
==20392== 
==20392== All heap blocks were freed -- no leaks are possible
==20392== 
==20392== Use --track-origins=yes to see where uninitialised values come from
==20392== For lists of detected and suppressed errors, rerun with: -s
==20392== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
[root@lwh testcpp]# 

3. cJSON作者Dave Gamble的CJSON使用例程


https://jaist.dl.sourceforge.net/project/cjson/ cJSONFiles.zip 2015-02-14 04:08 25K
压缩包里的 test.c 是2009年给出的


https://github.com/DaveGamble/cJSON/blob/master/tests/parse_examples.c
托管于GitHub上的,一直在迭代,
parse_examples.c 是把 test.c拆分为了几个文件 进行了一些改进 并加入了诸多错误检测,显得不那么紧凑 反而不利于新手学习


我们使用test.c作为学习案例

3.1 test.c

位于 /cJSONFiles/cJSON/ 目录下

/*
  Copyright (c) 2009 Dave Gamble
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

#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);
	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);
	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: */
	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);	printf("%s\n",out);	free(out);	/* Print to text, Delete the cJSON, print it, release the string. */

	/* Our "days of the week" array: */
	root=cJSON_CreateStringArray(strings,7);

	out=cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n",out);	free(out);

	/* Our matrix: */
	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);	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","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);	printf("%s\n",out);	free(out);

	/* Our array of "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),"City",cJSON_CreateIntArray(ids,4)); */
	
	out=cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n",out);	free(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\":      1920, \n\"height\":     1080, \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, 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;
}

3.2 json文件test[1-5]

位于 **/cJSONFiles/cJSON/tests/**目录下
test1

{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}

test2

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

test3

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}    

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": "SET NOCOUNT ON;select test='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"}}}

test5

{"menu": {
    "header": "SVG Viewer",
    "items": [
        {"id": "Open"},
        {"id": "OpenNew", "label": "Open New"},
        null,
        {"id": "ZoomIn", "label": "Zoom In"},
        {"id": "ZoomOut", "label": "Zoom Out"},
        {"id": "OriginalView", "label": "Original View"},
        null,
        {"id": "Quality"},
        {"id": "Pause"},
        {"id": "Mute"},
        null,
        {"id": "Find", "label": "Find..."},
        {"id": "FindAgain", "label": "Find Again"},
        {"id": "Copy"},
        {"id": "CopyAgain", "label": "Copy Again"},
        {"id": "CopySVG", "label": "Copy SVG"},
        {"id": "ViewSVG", "label": "View SVG"},
        {"id": "ViewSource", "label": "View Source"},
        {"id": "SaveAs", "label": "Save As"},
        null,
        {"id": "Help"},
        {"id": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}

3.3 编译运行

3.3.1 编译
[root@lwh testcpp]# gcc test.c -o testcjson -lcjson -std=c99

3.3.2 运行结果
[root@lwh testcpp]# ./testcjson 
{
        "name": "Jack (\"Bee\") Nimble",
        "format":       {
                "type": "rect",
                "width":        1920,
                "height":       1080,
                "interlace":    false,
                "frame rate":   24
        }
}
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[[0, -1, 0], [1, 0, 0], [0, 0, 1]]
{
        "Image":        {
                "Width":        800,
                "Height":       600,
                "Title":        "View from 15th Floor",
                "Thumbnail":    {
                        "Url":  "http:/*www.example.com/image/481989943",
                        "Height":       125,
                        "Width":        "100"
                },
                "IDs":  [116, 943, 234, 38793]
        }
}
[{
                "precision":    "zip",
                "Latitude":     37.7668,
                "Longitude":    -122.3959,
                "Address":      "",
                "City": "SAN FRANCISCO",
                "State":        "CA",
                "Zip":  "94107",
                "Country":      "US"
        }, {
                "precision":    "zip",
                "Latitude":     37.371991,
                "Longitude":    -122.02602,
                "Address":      "",
                "City": "SUNNYVALE",
                "State":        "CA",
                "Zip":  "94085",
                "Country":      "US"
        }]
{
        "name": "Jack (\"Bee\") Nimble",
        "format":       {
                "type": "rect",
                "width":        1920,
                "height":       1080,
                "interlace":    false,
                "frame rate":   24
        }
}
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[[0, -1, 0], [1, 0, 0], [0, 0, 1]]
{
        "Image":        {
                "Width":        800,
                "Height":       600,
                "Title":        "View from 15th Floor",
                "Thumbnail":    {
                        "Url":  "http:/*www.example.com/image/481989943",
                        "Height":       125,
                        "Width":        "100"
                },
                "IDs":  [116, 943, 234, 38793]
        }
}
[{
                "precision":    "zip",
                "Latitude":     37.7668,
                "Longitude":    -122.3959,
                "Address":      "",
                "City": "SAN FRANCISCO",
                "State":        "CA",
                "Zip":  "94107",
                "Country":      "US"
        }, {
                "precision":    "zip",
                "Latitude":     37.371991,
                "Longitude":    -122.026,
                "Address":      "",
                "City": "SUNNYVALE",
                "State":        "CA",
                "Zip":  "94085",
                "Country":      "US"
        }]

3.3.3 是否有内存泄漏
[root@lwh testcpp]# valgrind --leak-check=full ./testcjson
==24991== Memcheck, a memory error detector
==24991== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==24991== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==24991== Command: ./testcjson
==24991== 
{
        "name": "Jack (\"Bee\") Nimble",
        "format":       {
                "type": "rect",
                "width":        1920,
                "height":       1080,
                "interlace":    false,
                "frame rate":   24
        }
}
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[[0, -1, 0], [1, 0, 0], [0, 0, 1]]
{
        "Image":        {
                "Width":        800,
                "Height":       600,
                "Title":        "View from 15th Floor",
                "Thumbnail":    {
                        "Url":  "http:/*www.example.com/image/481989943",
                        "Height":       125,
                        "Width":        "100"
                },
                "IDs":  [116, 943, 234, 38793]
        }
}
[{
                "precision":    "zip",
                "Latitude":     37.7668,
                "Longitude":    -122.3959,
                "Address":      "",
                "City": "SAN FRANCISCO",
                "State":        "CA",
                "Zip":  "94107",
                "Country":      "US"
        }, {
                "precision":    "zip",
                "Latitude":     37.371991,
                "Longitude":    -122.02602,
                "Address":      "",
                "City": "SUNNYVALE",
                "State":        "CA",
                "Zip":  "94085",
                "Country":      "US"
        }]
{
        "name": "Jack (\"Bee\") Nimble",
        "format":       {
                "type": "rect",
                "width":        1920,
                "height":       1080,
                "interlace":    false,
                "frame rate":   24
        }
}
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[[0, -1, 0], [1, 0, 0], [0, 0, 1]]
{
        "Image":        {
                "Width":        800,
                "Height":       600,
                "Title":        "View from 15th Floor",
                "Thumbnail":    {
                        "Url":  "http:/*www.example.com/image/481989943",
                        "Height":       125,
                        "Width":        "100"
                },
                "IDs":  [116, 943, 234, 38793]
        }
}
[{
                "precision":    "zip",
                "Latitude":     37.7668,
                "Longitude":    -122.3959,
                "Address":      "",
                "City": "SAN FRANCISCO",
                "State":        "CA",
                "Zip":  "94107",
                "Country":      "US"
        }, {
                "precision":    "zip",
                "Latitude":     37.371991,
                "Longitude":    -122.026,
                "Address":      "",
                "City": "SUNNYVALE",
                "State":        "CA",
                "Zip":  "94085",
                "Country":      "US"
        }]
==24991== 
==24991== HEAP SUMMARY:
==24991==     in use at exit: 0 bytes in 0 blocks
==24991==   total heap usage: 258 allocs, 258 frees, 14,142 bytes allocated
==24991== 
==24991== All heap blocks were freed -- no leaks are possible
==24991== 
==24991== For lists of detected and suppressed errors, rerun with: -s
==24991== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[root@lwh testcpp]# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值