demon如下
#include <stdio.h>
#include "cJSON.h"
char *creat_json()
{
char *creat_json = NULL;
cJSON *json=NULL;
cJSON *province=NULL;
cJSON *twcityArray=NULL;
/*1.初始化*/
//建立一個json物件,返回一個cJSON結構體型別的指針。
json=cJSON_CreateObject();
//建立一個json物件,返回一個cJSON結構體型別的指針。
province=cJSON_CreateObject();
twcityArray = cJSON_CreateArray();
/*2.填充初始化的結構體型別*/
//向jison物件中新增字串
cJSON_AddStringToObject(json, "country", "中國");
cJSON_AddStringToObject(province, "name", "臺灣");
//向陣列物件中新增一個元素
cJSON_AddItemToArray(twcityArray, cJSON_CreateString("臺北"));
cJSON_AddItemToArray(twcityArray, cJSON_CreateString("高雄"));
/*3.結構體巢狀填充*/
//向cJSON結構體province中新增cityArray陣列物件
cJSON_AddItemToObject(province, "city", twcityArray);
//向cJSON結構體json中新增province的cJSON結構體
cJSON_AddItemToObject(json, "province", province);
//cJSON_Print(json)將一個cJSON結構體代表的json物件轉換爲一個json格式的字串
creat_json=cJSON_Print(json);
printf("%s\n", creat_json);
return creat_json;
}
int main()
{
int i;
cJSON *cJSON_object = NULL;
cJSON *country = NULL;
cJSON *province = NULL;
cJSON *province_name = NULL;
cJSON *city_name = NULL;
const char *json=creat_json();
cJSON_object = cJSON_Parse(json);
//解析國家
country = cJSON_GetObjectItem(cJSON_object, "country");
printf("解析country:%s\n",country->valuestring);
//解析省份
province = cJSON_GetObjectItem(cJSON_object,"province");
province_name = cJSON_GetObjectItem(province, "name");
printf("解析province name:%s\n",province_name->valuestring);
//解析市
city_name=cJSON_GetObjectItem(province, "city");
int count = cJSON_GetArraySize(city_name);
printf("解析city:");
for(i=0;i<count;i++)
{
cJSON *cityItem = cJSON_GetArrayItem(city_name, i);
printf("%s ",cityItem->valuestring);
}
printf("\n");
return 0;
}
Makefile
LDFLAGS = -lm
OBJES = cJSON.o creat_json.o
creat_json: $(OBJES)
gcc $(OBJES) -o creat_json $(LDFLAGS)
test.o:creat_json.c cJSON.h
gcc -c creat_json.c -o creat_json.o
cJSON.o:cJSON.c cJSON.h
gcc -c cJSON.c -o cJSON.o
clean:
rm -rf *.o creat_json