上文学习了cJSON库的一些理论知识,接下来开始进行实战.
从一个json文件中读取并解析这个文件.
资源文件内容res.json
:
{
"config_appl": "file",
"version": "0.1.0",
"resources": {
"key_p": "NA",
"key_n": "WO",
"key_e": "local",
"key_ze": "na",
"key_le": "na",
"key_name": "na",
"key_type": "file",
"key_ID": "na"
}
}
test.c
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"cJSON.h"
char* read_file(const char *filename) {
FILE *file = NULL;
long length = 0;
char *content = NULL;
size_t read_chars = 0;
/* open in read binary mode */
file = fopen(filename, "rb");
if (file == NULL)
{
goto cleanup;
}
/* get the length */
if (fseek(file, 0, SEEK_END) != 0)
{
goto cleanup;
}
length = ftell(file);
if (length < 0)
{
goto cleanup;
}
if (fseek(file, 0, SEEK_SET) != 0)
{
goto cleanup;
}
/* allocate content buffer */
content = (char*)malloc((size_t)length + sizeof(""));
if (content == NULL)
{
goto cleanup;
}
/* read the file into memory */
read_chars = fread(content, sizeof(char), (size_t)length, file);
if ((long)read_chars != length)
{
free(content);
content = NULL;
goto cleanup;
}
content[read_chars] = '\0';
cleanup:
if (file != NULL)
{
fclose(file);
}
return content;
}
int main()
{
char *json_file;
cJSON * json_tmp;
cJSON * ch, *key_ch;
int size;
int kye_size;
int i, j;
//使用官网函数读取文件(test/common.c)
json_file = read_file("res.json");
//解析json
json_tmp = cJSON_Parse(json_file);
//获取当前key值数量
size = cJSON_GetArraySize(json_tmp);
printf("%d\n", size);
//判断数据类型
ch = json_tmp->child;
for(i = 0; i < size; i++){
printf("[num=%d] [type=%d]\n", i, ch->type);
ch = ch->next;
}
//打印每一个key值
ch = json_tmp->child;
for(i = 0; i < size; i++){
if(cJSON_IsObject(ch)){
kye_size = cJSON_GetArraySize(ch);
key_ch = ch->child;
printf("[num=%d ]\n", i);
printf("[key=%s]\n", ch->string);
printf("----------------------\n");
for(j = 0; j < kye_size; j++){
printf("[value_num=%d ]\n", j);
printf("[key=%s]\n[value=%s]\n", key_ch->string, key_ch->valuestring);
key_ch = key_ch->next;
}
printf("----------------------\n");
}else{
printf("[num=%d ]\n", i);
printf("[key=%s]\n[value=%s]\n", ch->string, ch->valuestring);
}
ch = ch->next;
}
}
编译执行命令:
gcc test.c cJSON.c -lm
运行结果:
image.png