为了更方便使用C的JSON库,对其进行了一层封装。

H文件:

 #ifndef __JSONHELPER__
#define __JSONHELPER__ #ifdef __cplusplus
extern "C"
{
#endif #define JSON_NAME_MAX_SIZE 128 enum
{
JSON_OK = ,
JSON_ERROR,
JSON_ERR_NO_SUCH_NODE,
JSON_ERR_INVALID_NODE,
JSON_ERR_NO_SUCH_ARRAY,
JSON_ERR_INVALID_ARRAY_INDEX,
JSON_ERR_UNMATCH_TYPE
}; #define JSON_ERROR_STRING "Okay\0" \
"Error\0" \
"No Such Node\0" \
"Invalid Node\0" \
"No Such Array\0" \
"Invalid Array Index\0" \
"Unmatch Type\0" const char *jsonNodeType(void *json);
const char *jsonErrorString(int ret); void *jsonParse(const char *text);
void jsonDelete(void *json);
void jsonDumpError(const char *text);
void jsonDump(void *json); char *jsonToString(void *json, int format);
char *jsonToBuffer(void *json, int format, char *buffer, int len); int jsonTestNumber(void *json);
int jsonTestString(void *json);
int jsonTestArray(void *json);
int jsonTestObject(void *json);
int jsonTestBool(void *json); void *jsonGetNode(void *json, const char *node, int *ret);
int jsonGetString(void *json, const char *node, char *buf, int len);
int jsonGetInt(void *json, const char *node, int *value);
int jsonGetBool(void *json, const char *node, int *value);
int jsonGetUint64(void *json, const char *node, unsigned long long *value);
int jsonGetArraySize(void *json);
void *jsonGetArrayItem(void *json, int item);
int *jsonGetIntArray(void *json, const char *node, int *size); int jsonMatchString(void *json, const char *node, char *value);
int jsonMatchInt(void *json, const char *node, int value);
int jsonMatchBool(void *json, const char *node, int value);
int jsonMatchUint64(void *json, const char *node, unsigned long long value); int jsonSetString(void *json, const char *node, const char *str);
int jsonSetInt(void *json, const char *node, int value);
int jsonSetBool(void *json, const char *node, int value);
int jsonSetUint64(void *json, const char *node, unsigned long long value); void *jsonDuplicate(void *json, int withChild); #define jsonNewRoot() jsonNewOject(NULL, NULL)
void *jsonNewOject(void *json, const char *name);
void *jsonNewArray(void *json, const char *name);
void *jsonArrayAddItem(void *array); void *jsonAttach(void *json, const char *name, void *obj); void *jsonAddBool(void *json, const char *name, int b);
void *jsonAddInt(void *json, const char *name, int v);
void *jsonAddDouble(void *json, const char *name, double v);
void *jsonAddUint64(void *json, const char *name, unsigned long long v);
void *jsonAddString(void *json, const char *name, const char *str);
void *jsonAddIntArray(void *json, const char *name, const int *numbers,int count);
void *jsonAddStringArray(void *json, const char *name, const char **str, int count); #ifdef __cplusplus
}
#endif #endif /* __JSONHELPER__ */

C文件:

 /*
@File: jsonHelper.c
@Description: json helper functions
@Date: 2018-04-27
@Author: Liu Chuansen (179712066@qq.com) */ #include <stdio.h>
#include <string.h>
#include <stdlib.h> #include "jsonHelper.h"
#include "cJSON.h" static const char *cJsonType(int type)
{
const char *p = "False\0True\0NULL\0Number\0String\0Array\0Object\0";
int i = ; if (type == )
{
return p;
} while(*p)
{
p ++;
if (*p == '\0')
{
i ++;
p ++;
if (*p && (i == type))
{
return p;
}
}
} return "[Unknown]";
} const char *jsonNodeType(void *json)
{
return cJsonType(((cJSON *)json)->type);
} const char *jsonErrorString(int ret)
{
const char *p = JSON_ERROR_STRING;
int i = ; if (ret == )
{
return p;
} while(*p)
{
p ++;
if (*p == '\0')
{
i ++;
p ++;
if (*p && (i == ret))
{
return p;
}
}
} return "[Unknown]";
} void *jsonParse(const char *text)
{
return cJSON_Parse(text);
} void jsonDelete(void *json)
{
return cJSON_Delete(json);
} /*
@input: text, origin text pass to jsonParse
@desc: only call this function when jsonParse() failed
*/
void jsonDumpError(const char *text)
{
static char buffer[];
int len = strlen(text);
const char *p = cJSON_GetErrorPtr(); printf("------------json error dump------------\n"); if (p && (p < text + len))
{
const char *pre = text;
int preLen = ;
int offset = ; if ((p - text) > )
{
pre = p - ;
}
else {
preLen = p - text;
} if (preLen > )
{
strncpy(buffer, pre, preLen);
strcpy(buffer + preLen, "\\_/");
offset = preLen + ;
} strncpy(buffer + offset, p, sizeof(buffer) - offset - );
buffer[sizeof(buffer) - ] = ; printf("%s\n", buffer);
}
else
{
printf("***Unable to find error text\n");
} printf("=======================================\n");
} void jsonDump(void *json)
{
printf("---------------json dump---------------\n"); char *d = cJSON_Print(json);
printf("%s\n", d ? d : "(null)");
printf("=======================================\n"); if (d)
{
free(d);
}
} char *jsonToString(void *json, int format)
{
return format ? cJSON_Print(json) : cJSON_PrintUnformatted(json);
} char *jsonToBuffer(void *json, int format, char *buffer, int len)
{
if (!buffer || !len)
{
return "Buffer is not valid";
} return cJSON_PrintToBuffer(json, buffer, len, format);
} int jsonTestNumber(void *json)
{
if (json == NULL) return ;
return (((cJSON *)json)->type == cJSON_Number) ? : ;
} int jsonTestString(void *json)
{
if (json == NULL) return ;
return (((cJSON *)json)->type == cJSON_String) ? : ;
} int jsonTestArray(void *json)
{
if (json == NULL) return ;
return (((cJSON *)json)->type == cJSON_Array) ? : ;
} int jsonTestObject(void *json)
{
if (json == NULL) return ;
return (((cJSON *)json)->type == cJSON_Object) ? : ;
} int jsonTestBool(void *json)
{
cJSON *j = json;
if (j == NULL) return ; if ((j->type == cJSON_False) || (j->type == cJSON_True))
{
return ;
} if ((j->type == cJSON_Number) && ((j->valueint == ) || (j->valueint == )))
{
return ;
} return ;
} /*
@function: jsonGetNode
---
@json: json parent node
@node: node path, such as "sys.info[0].root"
@ret: return status
---
@return the node handle of destination node
*/ void *jsonGetNode(void *json, const char *node, int *ret)
{
cJSON *s;
const char *subItem = NULL;
const char *p;
char *pe;
char item[JSON_NAME_MAX_SIZE + ];
int len, index = -; if ((node == NULL) || (*node == '\0'))
{
*ret = JSON_ERR_INVALID_NODE;
return NULL;
} /* split first node name */
p = strchr(node, '.'); if (p)
{
len = p - node;
subItem = p + ;
}
else
{
len = strlen(node);
} if (!len || (len > sizeof(item) - ))
{
*ret = JSON_ERR_INVALID_NODE;
return NULL;
} strncpy(item, node, len);
item[len] = '\0'; /* get array if it is */
pe = strchr(item, '[');
if (pe)
{
*pe = '\0';
index = strtoul(pe + , NULL, );
} s = cJSON_GetObjectItem(json, item); if (s && (index >= ))
{ if (s->type != cJSON_Array)
{
*ret = JSON_ERR_NO_SUCH_ARRAY;
return NULL;
} if (index >= cJSON_GetArraySize(s))
{
*ret = JSON_ERR_INVALID_ARRAY_INDEX;
return NULL;
} s = cJSON_GetArrayItem(s, index);
} if (s == NULL)
{
*ret = JSON_ERR_NO_SUCH_NODE;
return NULL;
} if (subItem)
{
return jsonGetNode(s, subItem, ret);
}
else
{
*ret = JSON_OK;
return s;
}
} int jsonGetString(void *json, const char *node, char *buf, int len)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestString(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if (buf && len)
{
strncpy(buf, d->valuestring, len - );
buf[len - ] = '\0';
} return JSON_OK;
} int jsonGetInt(void *json, const char *node, int *value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestNumber(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if (value)
{
*value = d->valueint;
} return JSON_OK;
} int jsonGetBool(void *json, const char *node, int *value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestBool(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if (value)
{
if (d->type == cJSON_True)
{
*value = ;
}
else if (d->type == cJSON_Number)
{
*value = d->valueint ? : ;
}
else
{
*value = ;
}
} return JSON_OK;
} int jsonGetUint64(void *json, const char *node, unsigned long long *value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestNumber(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if (value)
{
*value = d->valueuint64;
} return JSON_OK;
} /* need to free */
int *jsonGetIntArray(void *json, const char *node, int *size)
{
int ret = JSON_OK;
int num;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json;
int *intArray = NULL;
int i; if (ret != JSON_OK) return ret; if (!jsonTestArray(d))
{
return NULL;
} num = cJSON_GetArraySize(d); if (num > )
{
intArray = malloc(sizeof(num) * sizeof(int)); for (i = ; i < num; i ++)
{
cJSON *s = cJSON_GetArrayItem(d, i);
if (s->type != cJSON_Number)
{
free(intArray);
return NULL;
}
intArray[i] = s->valueint;
}
} if (size)
{
*size = num;
} return intArray;
} int jsonGetArraySize(void *json)
{
if (!jsonTestArray(json))
{
return ;
} return cJSON_GetArraySize(json);
} void *jsonGetArrayItem(void *json, int item)
{
if (!jsonTestArray(json))
{
return NULL;
} return cJSON_GetArrayItem(json, item);
} int jsonMatchString(void *json, const char *node, char *value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ; if (!jsonTestString(d))
{
return ;
} if (value)
{
return !strcmp(value, d->valuestring) ? : ;
} return ;
} int jsonMatchInt(void *json, const char *node, int value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ; if (!jsonTestNumber(d))
{
return ;
} return (value == d->valueint) ? : ;
} int jsonMatchBool(void *json, const char *node, int value)
{
int ret = JSON_OK, bv;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ; if (!jsonTestBool(d))
{
return ;
} if (d->type == cJSON_True)
{
bv = ;
}
else if (d->type == cJSON_Number)
{
bv = d->valueint ? : ;
}
else
{
bv = ;
} if (value > )
{
value = ;
} return (bv == value) ? : ;
} int jsonMatchUint64(void *json, const char *node, unsigned long long value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ; if (!jsonTestNumber(d))
{
return ;
} return (value == d->valueuint64) ? : ;
} /* it is not safe function */
int jsonSetString(void *json, const char *node, const char *str)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestString(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if (str && str[])
{
if (!(d->type & cJSON_IsReference) && d->valuestring)
{
free(d->valuestring);
} d->valuestring = strdup(str);
} return JSON_OK;
} int jsonSetInt(void *json, const char *node, int value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestNumber(d))
{
return JSON_ERR_UNMATCH_TYPE;
} d->valueint = value;
d->valuedouble = (double)value;
d->valueuint64 = ; return JSON_OK;
} int jsonSetBool(void *json, const char *node, int value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestBool(d))
{
return JSON_ERR_UNMATCH_TYPE;
} if ((d->type == cJSON_True) || (d->type == cJSON_False))
{
d->type = value ? cJSON_True : cJSON_False;
}
else if (d->type == cJSON_Number)
{
d->valueint = value ? : ;
d->valuedouble = (double)d->valueint;
d->valueuint64 = ;
} return JSON_OK;
} int jsonSetUint64(void *json, const char *node, unsigned long long value)
{
int ret = JSON_OK;
cJSON *d = node ? jsonGetNode(json, node, &ret) : json; if (ret != JSON_OK) return ret; if (!jsonTestNumber(d))
{
return JSON_ERR_UNMATCH_TYPE;
} d->valueuint64 = value; return JSON_OK;
} void *jsonDuplicate(void *json, int withChild)
{
return cJSON_Duplicate(json, withChild);
} void *jsonNewOject(void *json, const char *name)
{
cJSON *j = cJSON_CreateObject();
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
}
return j;
} void *jsonNewArray(void *json, const char *name)
{
cJSON *j = cJSON_CreateArray();
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
}
return j;
} void *jsonArrayAddItem(void *array)
{
cJSON *j = cJSON_CreateObject();
if (array)
{
cJSON_AddItemToArray(array, j);
}
return j;
} void *jsonAttach(void *json, const char *name, void *obj)
{
cJSON_AddItemToObject(json, name, obj); return obj;
} void *jsonAddBool(void *json, const char *name, int b)
{
cJSON *j = cJSON_CreateBool(b);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddInt(void *json, const char *name, int v)
{
cJSON *j = cJSON_CreateNumber(v);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddDouble(void *json, const char *name, double v)
{
cJSON *j = cJSON_CreateNumber(v);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddUint64(void *json, const char *name, unsigned long long v)
{
cJSON *j = cJSON_CreateUint64(v);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddString(void *json, const char *name, const char *str)
{
cJSON *j = cJSON_CreateString(str);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddIntArray(void *json, const char *name, const int *numbers,int count)
{
cJSON *j = cJSON_CreateIntArray(numbers, count);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
} void *jsonAddStringArray(void *json, const char *name, const char **str, int count)
{
cJSON *j = cJSON_CreateStringArray(str, count);
if (json && name)
{
cJSON_AddItemToObject(json, name, j);
} return j;
}

后续将提供使用示例。

CJSON的封装API的更多相关文章

  1. vue项目,封装api并使用

    封装api index.js let uploadBase = '' if(process.env.NODE_ENV === 'production'){ uploadBase = 'https:// ...

  2. Lucene.Net的服务器封装+APi组件 (开源)

    为什么要封装 真不知道用什么标题合适,我这几天在研究Lucene.Net,觉得把Lucene.Net封装为一个独立的服务器,再提供一个给客户端调用的Api组件应该是一件很意思的事,主要优势有以下: 1 ...

  3. QT全局热键(用nativeKeycode封装API,不跨平台)

    在网上找了很长时间,大家都提到了一个QT全局热键库(qxtglobalshortcut),支持跨平台.在这篇文章中,我将只展示出windows平台下全局热键的设置. 这里提供的方法是在MyGlobal ...

  4. ceph rbd 封装api

    1.安装python,uwsgi,nginx环境 pip安装省略 yumgroupinstall"Developmenttools" yuminstallzlib-develbzi ...

  5. vue项目实践-添加axios封装api请求

    安装 axios npm install axios --save 创建实例 (utils/fetch.js) axios 默认提交格式为:application/json 可使用 qs 模块(需要安 ...

  6. 前后分离模型之封装 Api 调用

    Ajax 和异步处理 调用 API 访问数据采用的 Ajax 方式,这是一个异步过程,异步过程最基本的处理方式是事件或回调,其实这两种处理方式实现原理差不多,都需要在调用异步过程的时候传入一个在异步过 ...

  7. 如何在项目中封装api

    一般在项目中,会有很多的api请求,无论在vue,angular,还是react中都应该把接口封装起来,方便后期的维护. 1.新建一个api文件 我们可以在项目的分目录下创建一个api文件夹,在这里面 ...

  8. Vue实例中封装api接口的思路 在页面中用async,await调用方法请求

    一般我们写小型的项目是用不到封装axios实例 但是当我们写大型项目时  接口有时候多到有上百个接口,那我们在请求一次调用一次接口,接口上好多都是重复的,这个时候我们就可以封装axios实例,既节省了 ...

  9. vue项目 封装api

    设计思路 为了加强项目的可维护性,建议将请求接口api进行统一封装, 一个常规项目的基础地址一般为唯一,所以考虑将基础地址设定一个变量 let  baseUrl: "xxxxxx" ...

随机推荐

  1. CentOS-Apache服务(1)

    title date tags layout CentOS6.5 配置Apache及多站点VirtualHost 2018-08-29 Centos6.5服务器搭建 post 1.安装httpd服务 ...

  2. android基于MVP小说网络爬虫、宝贝社区APP、仿虎扑钉钉应用、滑动阴影效果等源码

    Android精选源码 android宝贝社区app源码 android仿Tinder最漂亮的一个滑动效果 android仿滴滴打车开具发票页,ListView粘性Header Android基于MV ...

  3. 吴裕雄--天生自然python学习笔记:python爬虫PM2.5 实时监测显示器

    PM2.5 对人体的健康影响很大,所以空气中的 PM2.5 实时信息受到越来越多的关注. Python 的 Pandas 套件不但可以自动读取网页中的表格 数据 , 还可对数据进行修改.排序等处理,也 ...

  4. hdu6582

    题意:给定一个无向图,删除某些边有一定的代价,要求删掉使得最短路径减小,求最小代价. 分析:首先要spfa求出起点到各个点的最短距离.对于一条权值为w,起点为i,终点为j的边,设dis[k]为起点到k ...

  5. OpenCV、EmguCV函数注解

  6. Mybatis与Spring整合(纯注解)

    java1.5版本之后开始支持注解,spring*2开始提供注解配置方式,到spring**4后spring推荐使用注解配置 IOC注解(主要作用就是在spring容器中声明一个Bean,同xml中的 ...

  7. Java IO: 字符流的Buffered和Filter

    作者: Jakob Jenkov  译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍缓冲与过滤相关的reader和writer,主要涉及BufferedReader.B ...

  8. JDK源码看Java域名解析

    前言 在互联网中通信需要借助 IP 地址来定位到主机,而 IP 地址由很多数字组成,对于人类来说记住某些组合数字很困难,于是,为了方便大家记住某地址而引入主机名和域名. 早期的网络中的机器数量很少,能 ...

  9. <luogu1347>排序

    本来打算当打了个拓扑的板子 后来发现并不只是个板子 差不多 管他呢 #include<cstdio> #include<cstring> #include<iostrea ...

  10. 吴裕雄--天生自然 R语言开发学习:图形初阶

    # ----------------------------------------------------# # R in Action (2nd ed): Chapter 3 # # Gettin ...