为了更方便使用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. python取出前端传入execl文件中的数据

    from openpyxl import load_workbook #获取前台传入的文件 uploadedFile = request.FILES.get('file') #获取execl文件 wb ...

  2. STL:map中的lower_bound和upper_bound

    今天在做leetcode的Longest Increasing Subsequence题目时,需要用到二分查找,于是翻看了<STL源码剖析>这本书,发现map里面有lower_bound和 ...

  3. org.apache.http.NoHttpResponseException

    org.apache.http.NoHttpResponseException 异常: org.apache.http.NoHttpResponseException: The target serv ...

  4. 使用记事本编写html代码并运行

    在使用记事本编写html代码,运行时需要将其.txt后缀改为.html双击运行即可. 有时电脑会默认的隐藏其后缀,这时需要修改一下. win7系统修改方法: 双击  我的电脑: 选择  组织: 选择  ...

  5. com.spotify:docker-maven-plugin 报localhost:2375 Connection refused 错误

    当用maven build项目时出现了如下错误: Failed to execute goal com.spotify:docker-maven-plugin:0.4.13:build (defaul ...

  6. springmvc拦截器入门及其执行顺序源码分析

    springmvc拦截器是偶尔会用到的一个功能,本案例来演示一个较简单的springmvc拦截器的使用,并通过源码来分析拦截器的执行顺序的控制.具体操作步骤为:1.maven项目引入spring依赖2 ...

  7. python标准库:datetime模块

    原文地址:http://www.bugingcode.com/blog/python_datetime.html datatime 模块题共用一些处理日期,时间和时间间隔的函数.这个模块使用面向对象的 ...

  8. Rime输入法一些设定

    有鉴于谷歌搜狗拼音等不太好用,但是博主一直页没找到合心的输入法,直到遇见Rime,中州韵就是我想要的输入法.记录一下自己用的时候的修改,以备查询.注意:缩进不要弄丢,所有更改完都需要重新部署才能生效. ...

  9. 7/8段码管(LED)

    LED显示器在许多的数字系统中作为显示输出设备,使用非常广泛.它的结构是由发光二极管构成的a.b.c.d.e.f和g七段,并由此得名,实际上每个LED还有一个发光段dp,一般用于表示小数点,所以也有少 ...

  10. Vue数据绑定(一)

    Contents Vue作为当下炙手可热的前端三大框架之一,一直都想深入研究一下其内部的实现原理,去学习MVVM模式的精髓.如果说MVVM是当下最流行的图形用户界面开发模式,那么数据绑定则是这一模式的 ...