当前位置:网站首页>Use of cjson Library
Use of cjson Library
2022-07-23 21:54:00 【Persimmon wind year】
MQTT+JSON It is the most commonly used communication protocol for data interaction of Internet of things devices , among JSON The protocol is very suitable for plaintext transmission 、 Scenario of short packet transmission .
Know, understand and apply design a protocol , Be sure to understand its principle first , Then go to know its advantages and disadvantages and scope of application .
Catalog
2、cJSON Possible modifications to the Library
2.2 Print number The emergence of scientific counting ( Reference resources )
3、JSON General methods of parsing and processing
3.4 Often used JSON Processing function
1、JSON Concept expression
JSON A data structure is a serialized object or array of key value pairs .
key , Is a string ;
value , It can be the object , Array , Numbers , One of the strings ;
The object is enclosed by curly braces and separated by commas ;
The array is enclosed by square brackets , The string is surrounded by double quotation marks , Both are separated by commas ;
Numbers don't need to be enclosed , Separate them directly with commas .
Its essence is a string , Can cross language 、 Cross platform storage , And string key-value The form is easy to read .
cJSON Library is one of the most typical C Language JSON Library code .
It is very suitable for transplantation and use on embedded devices .
2、cJSON Possible modifications to the Library
2.1 Memory modification
By default, this library uses C Memory function of standard library .
If you need to debug memory problems , Or you need to unify memory usage , You can change the code in the following location to replace the memory function .
#if defined(_MSC_VER)
/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
static void * CJSON_CDECL internal_malloc(size_t size)
{
return malloc(size);
}
static void CJSON_CDECL internal_free(void *pointer)
{
free(pointer);
}
static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
{
return realloc(pointer, size);
}
#else
#define internal_malloc malloc
#define internal_free free
#define internal_realloc realloc
#endif2.2 Print number The emergence of scientific counting ( Reference resources )
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer);
Document No 511 That's ok , This function performs sscanf after , Will cause printing number Type value , The result is the problem of scientific counting (stm32F205 During chip debugging , At that time, memory resources were extremely tight ).
The modification scheme is as follows ( Solve after modification ):
I don't know the specific reason , Just list the solutions first .
#if 0
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
length = sprintf((char*)number_buffer, "%1.15g", d);
/* Check whether the original double can be recovered */
if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
{
/* If not, print with 17 decimal places of precision */
length = sprintf((char*)number_buffer, "%1.17g", d);
}
#else
length = sprintf((char*)number_buffer, "%d", (unsigned int)d);
#endif3、JSON General methods of parsing and processing
3.1 Definition
// The necessary contents of the header file include relationships and declarations
#include "cJSON.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef enum
{
ERROR_CODE_INTER = -1, // internal error
ERROR_CODE_NONE = 0, // empty /OK
ERROR_CODE_PARAM, // Parameter error
} EnErrorCode;
typedef struct
{
char *CmdStr;
int (*CmdFun)(cJSON*);
} TyJsonCmdFun;
void JsonCmdAnalysis(uint8_t *pData, uint16_t unDataLen);
void JsonCmdResponse(cJSON *Json, int err, void *res);
void JsonCmdSend(uint8_t *pData, uint16_t unDataLen);Above , Defined ① The error code returned by the function ,②json Function structure ,③ The entrance of function analysis and feedback .
3.2 analysis JSON
Based on this , Sure Define the following function table ,
When receiving data to parse , Judge json Fixed key value pair of - Such as "cmd" Field , To execute the corresponding processing function .
Here is a point to pay attention to :cJSON_Parse and cJSON_Delete.
cJSON_Parse The function is used to flow bytes into JSON object , There is a memory request action , And can't get through free To release , Only through cJSON_Delete To release .
int JsonCmdDeal_version(cJSON *Json);
int JsonCmdDeal_ota_start(cJSON *Json);
int JsonCmdDeal_ota_data(cJSON *Json);
int JsonCmdDeal_ota_end(cJSON *Json);
int JsonCmdDeal_driver_test(cJSON *Json);
const static TyJsonCmdFun JsonCmdFunTable[] =
{
{"version", JsonCmdDeal_version},
{"ota_start", JsonCmdDeal_ota_start},
{"ota_data", JsonCmdDeal_ota_data},
{"ota_end", JsonCmdDeal_ota_end},
{"driver_test", JsonCmdDeal_driver_test},
};
void JsonCmdAnalysis(uint8_t *pData, uint16_t unDataLen)
{
uint8_t i;
cJSON *JsonCmd = NULL;
JsonCmd = cJSON_Parse((char*)pData);
if(JsonCmd != NULL)
{
for(i=0;i<sizeof(JsonCmdFunTable)/sizeof(TyJsonCmdFun);i++)
{
if(strcmp(JsonCmdFunTable[i].CmdStr,cJSON_GetObjectItem(JsonCmd,"cmd")->valuestring) == 0)
{
JsonCmdFunTable[i].CmdFun(JsonCmd);
break;
}
}
cJSON_Delete(JsonCmd);
}
}3.2 feedback / Generate JSON
void JsonCmdResponse(cJSON *Json, int err, void *res)
{
char *json_buf = NULL;
int buf_len = 0;
cJSON* respond_json = NULL;
respond_json = cJSON_CreateObject();
if(respond_json != NULL)
{
cJSON_AddStringToObject(respond_json, "cmd", cJSON_GetObjectItem(Json,"cmd")->valuestring);
if(err == ERROR_CODE_NONE)
cJSON_AddStringToObject(respond_json, "rsq", "ok");
else
cJSON_AddNumberToObject(respond_json, "rsq", err);
json_buf = cJSON_PrintUnformatted(respond_json);
if(json_buf != NULL)
{
buf_len = strlen((char*)json_buf);
JsonCmdSend((uint8_t *)json_buf, buf_len);
free(json_buf);
}
cJSON_Delete(respond_json);
}
}
void JsonCmdSend(uint8_t *pData, uint16_t unDataLen)
{
//do nothing
}
int JsonCmdDeal_version(cJSON *Json)
{
int err = ERROR_CODE_NONE;
JsonCmdResponse(Json, err, NULL);
return err;
}alike ,cJSON_CreateObject() Function to create JSON object , And with the subsequent user call cJSON_AddXXXXToObject Class generates a memory request (realloc), Finally, only by cJSON_Delete Free memory .
A little extra , Namely cJSON Of print function , Yes, it can be directly determined by free Function to release .
among ,cJSON_PrintUnformatted Yes, it will JSON Object is printed as a string without formatting characters .
cJSON_Print Is with formatting characters ( There will be many spaces and line breaks ).
If you need an intuitive view JSON data , Suggest using cJSON_Print;
But if it is application business execution , Suggest or use cJSON_PrintUnformatted, Minimize the amount of bytes transmitted .
3.4 Often used JSON Processing function
// Memory manipulation function
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);// String rotation json
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);// Print json character string 1
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);// Print json character string 2
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);// Release json
// establish json object
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);// establish json object
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);// Create array
// establish json object - Used to update key value pairs
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
// obtain json object
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);// Get array size
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);// Get an element of the array
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);// Get key value pairs
// add to json Key value pair
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
// Determine the value type of key value pair
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
// Replace ( to update ) Key value pair
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
边栏推荐
- Cookies and sessions
- lambda学习(sort后面的Comparator的使用,collection后使用Collectors.groupingBy分组)
- Yuanqi Digitalization: existing mode or open source innovation Lixia action
- 博客总排名为918
- Redis common commands correspond to redisson object operations
- Leaderboard design in game server
- PCL error: error c2589 "(": "::" illegal mark on the right)
- [arXiv] notes on uploading papers for the first time
- How to implement desktop lyrics in pyqt
- What are the product life cycle, common project functions, and information flow
猜你喜欢

阿里onedate分层思想

lambda學習(sort後面的Comparator的使用,collection後使用Collectors.groupingBy分組)

PCL error: error c2589 "(": "::" illegal mark on the right)

Principle and implementation of hash table, unordered set and mapping

Golang invalid argument to INTN

U++ events

Altium designer—Arduino UNO原理图&PCB图(自制Arduino板)

lambda学习(sort后面的Comparator的使用,collection后使用Collectors.groupingBy分组)

NLP field history most complete must read classic papers classification, sorting and sharing (with Chinese analysis)

Openlayers instances advanced mapbox vector tiles advanced mapbox vector maps
随机推荐
博客总排名为918
如何在 pyqt 中实现桌面歌词
集群聊天服务器:工程目录的创建
Compare kernelshap and treeshap based on speed, complexity and other factors
Redis常用命令对应到Redisson对象操作
query中的customer exit客户出口变量
DBSCAN point cloud clustering
Quick review of interview (III): probability theory and mathematical statistics
Comment forcer complètement le meurtre de processus indépendants de l'arrière - plan?
Introduction to database system fifth edition after class exercises - Chapter 1 Introduction
Apprentissage Lambda (utilisation du comparateur après tri, regroupement après collecte avec collectors.groupingby)
DBSCAN点云聚类
Distributed transaction scheme: best effort notification scheme
程序员成长第二十六篇:如何开好每日晨会?
U++ 学习笔记 控制物体Scale
Programmer growth Article 26: how to hold a good daily morning meeting?
&9 nodemon自动重启工具
Postgraduate entrance examination | advanced mathematics Chapter4 indefinite integral
User manual of boost filesystem
Redis common commands correspond to redisson object operations