CJSON的封装API
为了更方便使用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的更多相关文章
- vue项目,封装api并使用
封装api index.js let uploadBase = '' if(process.env.NODE_ENV === 'production'){ uploadBase = 'https:// ...
- Lucene.Net的服务器封装+APi组件 (开源)
为什么要封装 真不知道用什么标题合适,我这几天在研究Lucene.Net,觉得把Lucene.Net封装为一个独立的服务器,再提供一个给客户端调用的Api组件应该是一件很意思的事,主要优势有以下: 1 ...
- QT全局热键(用nativeKeycode封装API,不跨平台)
在网上找了很长时间,大家都提到了一个QT全局热键库(qxtglobalshortcut),支持跨平台.在这篇文章中,我将只展示出windows平台下全局热键的设置. 这里提供的方法是在MyGlobal ...
- ceph rbd 封装api
1.安装python,uwsgi,nginx环境 pip安装省略 yumgroupinstall"Developmenttools" yuminstallzlib-develbzi ...
- vue项目实践-添加axios封装api请求
安装 axios npm install axios --save 创建实例 (utils/fetch.js) axios 默认提交格式为:application/json 可使用 qs 模块(需要安 ...
- 前后分离模型之封装 Api 调用
Ajax 和异步处理 调用 API 访问数据采用的 Ajax 方式,这是一个异步过程,异步过程最基本的处理方式是事件或回调,其实这两种处理方式实现原理差不多,都需要在调用异步过程的时候传入一个在异步过 ...
- 如何在项目中封装api
一般在项目中,会有很多的api请求,无论在vue,angular,还是react中都应该把接口封装起来,方便后期的维护. 1.新建一个api文件 我们可以在项目的分目录下创建一个api文件夹,在这里面 ...
- Vue实例中封装api接口的思路 在页面中用async,await调用方法请求
一般我们写小型的项目是用不到封装axios实例 但是当我们写大型项目时 接口有时候多到有上百个接口,那我们在请求一次调用一次接口,接口上好多都是重复的,这个时候我们就可以封装axios实例,既节省了 ...
- vue项目 封装api
设计思路 为了加强项目的可维护性,建议将请求接口api进行统一封装, 一个常规项目的基础地址一般为唯一,所以考虑将基础地址设定一个变量 let baseUrl: "xxxxxx" ...
随机推荐
- VSTO作品:OutlookMailViewer的下载和使用
OutlookMailViewer用于Outlook 2013/2016的一款插件. 电脑的安装环境要求:具有VSTO运行环境+Net Framework 4.0以上. 下载地址: OutlookMa ...
- HQL语句简单介绍
HQL查询:Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Lanaguage)查询提供了更加丰富的和灵活的查询特性,因此 Hib ...
- iOS火焰动画效果、图文混排框架、StackView效果、偏好设置、底部手势等源码
iOS精选源码 高性能图文混排框架,构架顺滑的iOS应用. 使用OpenGLE覆盖阿尔法通道视频动画播放器视图. 可选最大日期截至当日日期的日期轮选器ChooseDatePicker 简单轻量的图片浏 ...
- the Uneducated are|anymore|that| so as to |die from|die of|
定冠词加上某些形容词可以泛指一类人,谓语动词一般用复数形式,the uneducated泛指未受过教育的人, the Uneducated are more to be pitied than bla ...
- makefile中的变量赋值
在makefile中赋值方式有:'='.':='.'?='和'+='. A = a $(B) B = b all: echo $(A) #运行结果:echo a b a b 这种赋值方式是没有先后顺序 ...
- 吴裕雄--天生自然 R语言开发学习:回归(续二)
#------------------------------------------------------------# # R in Action (2nd ed): Chapter 8 # # ...
- 两步解决maven plugins 插件下载慢 !下载报红的问题!
两步解决maven plugins 插件下载慢 !下载报红的问题! 1.找到你解压的maven安装路径下的conf 编辑settings 2.添加如下 使用阿里的 <mirror> ...
- 1122 Hamiltonian Cycle (25 分)
1122 Hamiltonian Cycle (25 分) The "Hamilton cycle problem" is to find a simple cycle that ...
- Python 字符编码判断
题记 在获取中文字符的时候,如果出现乱码的情况,我们需要了解当前的字符串的编码形式.使用下面两种方法可以判断字符串的编码形式. 法一: isinstance(s, str) 用来判断是否为一般字符串 ...
- 测试工程师不懂AI,还有未来吗?
阿里妹导读:近几年人工智能.机器学习等词漫天遍地,似乎有一种无AI,无研发,无AI,无测试的感觉.有人说:不带上"智能"二字,都不好意思说自己是创新.我们先暂且不评论对错,只探讨这 ...