#include <iostream>
#include "cJson/cJSON.h"
using namespace std;
void parse_json_node( cJSON * json,size_t * align_count )
{
// 打印缩进
for(int i = 0;i<*align_count;i++)
{
printf(" ");
}
switch(json->type)
{
case cJSON_False:
printf("%s : false",json->string);
break;
case cJSON_True:
printf("%s : true",json->string);
break;
case cJSON_NULL:
printf("null");
break;
case cJSON_Number:
printf("%s : %ll",json->string,json->valuedouble);
break;
case cJSON_String:
printf("%s : \"%s\"",json->string,json->valuestring);
break;
case cJSON_Array:
{
if(json->string)
{
printf("%s : ",json->string);
}
++*align_count;
printf("[\n");
int len = cJSON_GetArraySize(json);
for(int i = 0;i<len;i++)
{
cJSON * child_json = cJSON_GetArrayItem(json,i);
parse_json_node( child_json , align_count);
printf("\n");
}
--*align_count;
for(int i = 0;i<*align_count;i++)
{
printf(" ");
}
printf("]");
}
break;
case cJSON_Object:
{
if(json->string)
{
printf("%s : ",json->string);
}
++*align_count;
printf("{\n");
int len = cJSON_GetArraySize(json);
for(int i = 0;i<len;i++)
{
cJSON * child_json = cJSON_GetArrayItem(json,i);
parse_json_node( child_json , align_count);
printf("\n");
}
--*align_count;
for(int i = 0;i<*align_count;i++)
{
printf(" ");
}
printf("}");
}
break;
}
}
int main()
{
long long filesize = 0;
FILE * file = fopen("json/test5","rb+");
fseek(file,0,SEEK_END);
filesize = ftell(file);
fseek(file,0,SEEK_SET);
char * buff = new char[filesize];
fread(buff,1,filesize,file);
fclose(file);
cJSON * json = cJSON_Parse(buff);
size_t align_count = 0;
parse_json_node(json,&align_count);
/* cJSON * menu = cJSON_GetObjectItem(json,"menu");
int menu_size = cJSON_GetArraySize(menu);
cJSON * items = cJSON_GetArrayItem(menu,1);
int items_size = cJSON_GetArraySize(items);
cJSON * item1 = cJSON_GetArrayItem(items,0);
int item1_size = cJSON_GetArraySize(item1);
cJSON * item1_attr1 = cJSON_GetArrayItem(item1,0);
*/
return 0;
}简单明了,无需解释!
本文出自 “冰狐浪子的博客” 博客,请务必保留此出处http://bhlzlx.blog.51cto.com/3389283/1591089
原文:http://bhlzlx.blog.51cto.com/3389283/1591089