1. 概述:
该demo主要实现linux下JSON配置文件的基本操作,解析
引用cJSON库的地址为:https://github.com/DaveGamble/cJSON
2. 测试:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "cJSON.h"
void doit(char * text)
{
int i = 0, j = 0;
char * out = NULL;
cJSON * json = NULL;
json = cJSON_Parse(text);
if (!json) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
}
else{
out = cJSON_Print(json);
printf("%s\n\n", out);
free(out);
out = NULL;
cJSON * json_province = cJSON_GetArrayItem(json, 0);
out = cJSON_Print(json_province);
printf("%s\n", out);
free(out);
printf("name = %s\n\n", cJSON_GetObjectItem(json, "name")->valuestring);
cJSON * json_area = cJSON_GetArrayItem(json, 1);
out = cJSON_Print(json_area);
printf("%s\n", out);
free(out);
for(i = 0; i < cJSON_GetArraySize(json_area); i ++){
cJSON * json_city = cJSON_GetArrayItem(json_area, i);
if(NULL == json_city){
continue;
}
out = cJSON_Print(json_city);
printf("%s\n", out);
free(out);
for(j = 0; j < cJSON_GetArraySize(json_city); j ++ ){
cJSON * Citylist = cJSON_GetArrayItem(json_city, j);
if(NULL == Citylist){
continue;
}
printf("Citylist[%d] : %s\n", j, Citylist->valuestring);
}
}
cJSON_Delete(json);
}
}
void dofile(char * filename)
{
FILE * file = NULL;
long len = 0;
char * data = NULL;
file = fopen(filename, "rb");
fseek(file, 0, SEEK_END);
len = ftell(file);
fseek(file, 0, SEEK_SET);
data=(char*)malloc(len + 1);
fread(data, 1, len, file);
fclose(file);
doit(data);
free(data);
return ;
}
int main(int argc, char **argv){
dofile("./cjson");
return 0;
}
#Makefile
CC := gcc
AR := ar
all:
$(CC) -c cJSON.c -o cJSON.o -Wall -Werror
$(AR) cr libcJSON.a cJSON.o
#-L 指定库的路径 -l 指定需连接的库名
#-Wl,-Bstatic指示跟在后面的-lxxx选项链接的都是静态库
#-Wl,-Bdynamic指示跟在后面的-lxxx选项链接的都是动态库
$(CC) demo_cjson.c -o demo_cjson -lm -L. -Wl,-Bstatic -lcJSON -Wl,-Bdynamic -Wall -Werror
clean:
rm demo_cjson *.o *.a
{
"name": "黑龙江",
"cities": {
"city": ["哈尔滨", "大庆"]
}
}