1. 概述:
該demo主要實作linux下JSON組態檔的基本操作,決議
參考cJSON庫的地址為:https://github.com/DaveGamble/cJSON
2. 測驗:

/*
demo_cjson.c
cjson demo : JSON檔案的決議功能
參考 cJSON.h cJSON.c
github 地址 : https://github.com/DaveGamble/cJSON
*/
#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": ["哈爾濱", "大慶"]
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/274476.html
標籤:其他
上一篇:小程式訂餐系統——后端開發
