#include <stdio.h> #include <stdlib.h> #include "cJSON.h" 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) //如果對應鍵的值仍為cJSON_Object就遞歸調用printJson printJson(item); else //值不為json對象就直接打印出鍵和值 { printf("%s->", item->string); printf("%s\n", cJSON_Print(item)); } } } int main() { char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\"張三\"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\"打電話給張三\"}"; cJSON * root = NULL; cJSON * item = NULL;//cjson對象 root = cJSON_Parse(jsonStr); 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\n", "一步一步的獲取name 鍵值對:"); printf("%s\n", "獲取semantic下的cjson對象:"); item = cJSON_GetObjectItem(root, "semantic");// printf("%s\n", cJSON_Print(item)); printf("%s\n", "獲取slots下的cjson對象"); item = cJSON_GetObjectItem(item, "slots"); printf("%s\n", cJSON_Print(item)); printf("%s\n", "獲取name下的cjson對象"); item = cJSON_GetObjectItem(item, "name"); printf("%s\n", cJSON_Print(item)); printf("%s:", item->string); //看一下cjson對象的結構體中這兩個成員的意思 printf("%s\n", item->valuestring); printf("\n%s\n", "打印json所有最內層鍵值對:"); printJson(root); } return 0; }