代码下载地址: https://github.com/DaveGamble/cJSON
#include "cJSON.c"
struct Person{
int age;
const char *name;
};
void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{
for(int i=0; i<cJSON_GetArraySize(root); i++) //遍历最外层json键值对,就是遍历当前层次所有的键值对
{
cJSON * item = cJSON_GetArrayItem(root, i);
if(cJSON_Object == item->type)printJson(item); //如果对应键的值仍为cJSON_Object就递归调用printJson
else{ //值不为json对象就直接打印出键和值
printf("%s : ", item->string);
printf("%s\n", cJSON_Print(item));
}
}
}
int main() {
/******************
构建json对象并格式化成字符串输出
******************/
struct Person student[2] =
{
{
12,
"student_name1"
},
{
14,
"student_name2"
}
};
const char *subject[7] ={"yuwen", "shuxue", "yingyu"};
int chengji[3] = {60,65,70};//语文、数学、英语
const char *week[7] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
cJSON *root = NULL;
cJSON *student_point = NULL;
cJSON *chengji_point = NULL;
int today = 1;
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "class", cJSON_CreateString("1班"));
for (int i = 0; i < 2; i++)
{
cJSON_AddItemToObject(root, "student", student_point = cJSON_CreateObject());
cJSON_AddStringToObject(student_point, "name", student[i].name);
cJSON_AddNumberToObject(student_point, "age", student[i].age);
cJSON_AddStringToObject(student_point, "today", week[today]);
cJSON_AddFalseToObject (student_point, "is_late"); //是否迟到
cJSON_AddItemToObject(student_point, "chengji", chengji_point = cJSON_CreateObject());
for(int j=0; j<3; j++){
cJSON_AddNumberToObject(student_point, subject[j], chengji[j]);
}
}
char *string = cJSON_Print(root);
printf("%s\n", string);
cJSON_Delete(root);
root = cJSON_CreateObject();
root = cJSON_CreateStringArray(subject, 3);
root = cJSON_CreateIntArray(chengji, 3);
printf("%s\n", cJSON_Print(root));
cJSON_Delete(root);
/******************
由json字符串格式化为json对象并读取内容
******************/
root = cJSON_Parse(string);
if (!root) {
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}else{
printf("%s\n", "有格式的方式打印Json:");
printf("%s\n\n", cJSON_Print(root));
printf("%s\n", "无格式方式打印json:");
printf("%s\n\n", cJSON_PrintUnformatted(root));
//获取键名、键值
printf("%s : %s\n", cJSON_GetArrayItem(root,0)->string, cJSON_Print(cJSON_GetArrayItem(root,0)));
//获取class下的cjson对象
cJSON *item = NULL;
item = cJSON_GetObjectItem(root, "student");
printf("%s\n", cJSON_Print(item));
printf("\n%s\n", "打印json所有最内层键值对:");
printJson(root);
}
cJSON_Delete(root);
return 0;
}