使用go-zero微服务框架实现云监控后台(三.c语言操作cJson封装,json和结构体互转)

简介: 使用go-zero微服务框架实现云监控后台(三.c语言操作cJson封装,json和结构体互转)

c语言操作cJson封装,以及json和结构体互转。如果不做封装直接操作cJSON有点儿繁琐。


所以封装下是很有必要的,使用起来简单好用多了。


这是我计划的终端状态监控服务的终端部分的模块组件。


终端应用程序定时更新状态文件,应用中跑的另一个后台服务则定时读取该状态文件并上送至后台服务。以此无耦合的实现对终端的状态监控。参见:终端出厂后自动化运维方案_独行猫A 的沉淀、积累、总结。天天学习,好好向上...linux,Android,Vue,Go)-CSDN博客


下面是c语言读写json文件的简单封装,完成c语言结构体到json文件,json到结构体的转换。


#include "jsonopt.h"
/**
 * Function:GetArrayValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中获取ArrayItem内容
 */
int GetArrayValueString(cJSON* json,int id, char* name, char* param){
    cJSON* node;
    node = cJSON_GetArrayItem(json,id);
    if(!node){
        return -1;
    }
    sprintf(param, "%s", cJSON_GetObjectItem(node, name)->valuestring);
    return 0 ;
}
/**
 * Function:GetValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中读取字符串内容
 */
char* GetValueString(cJSON* json,char* name){
  cJSON* pObj = NULL;
    pObj = cJSON_GetObjectItem(json,name);
    if(pObj != NULL){
      return pObj->valuestring;
    }else{
      return NULL;
    }
}
/**
 * Function:GetValueInt
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中读取int类型值
 */
int GetValueInt(cJSON* json,char* name){
  cJSON* pObj = NULL;
    pObj = cJSON_GetObjectItem(json,name);
    if(pObj != NULL){
      return pObj->valueint;
    }else{
      return 0;
    }
}
/**
 * Function:SetValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 向json中的String类型字段赋值
 */
int SetValueString(cJSON* json,char* name,char* value){
  //printf("set key:%s,val:%s\n",name,value);
  if(cJSON_GetObjectItem(json,name)->valuestring != NULL){
    cJSON_ReplaceItemInObject(json,name,cJSON_CreateString(value));
  }else{
    //cJSON_AddItemToObject(json, name, cJSON_CreateString(value)); 
    cJSON_AddStringToObject(json, name, value);  
  }
  return 0;
}
/**
 * Function:SetValueInt
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 向json中的Int类型字段赋值
 */
int SetValueInt(cJSON* json,char* name,int value){
  cJSON* pObj = NULL;
  pObj = cJSON_GetObjectItem(json,name);
  if(pObj != NULL){
    pObj->valueint = value;
    pObj->valuedouble = value;
    return 0;
  }else{
    cJSON_AddNumberToObject(json, name, value); 
  }
  return 0;
}


/**
   * Copyright (C), 2021-2021,yangyongzhen 
   * File name:  jsonopt.h 
   * Author:   yangyongzhen
   * Version:  0.1
   * Date:                   2021-11-11 
   * Description:   c语言的cJSON操作封装
 **/
#ifndef _JSON_OPT_H_
#define _JSON_OPT_H_
#include <string.h>
#include "cJSON.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
 * Function:S2J_setInt
 * Description:Struct向Json的Int类型赋值
 * */
#define S2J_setInt(json,stru,element) SetValueInt(json,#element,(stru)->element)  
/**
 * Function:S2J_setString
 * Description:Struct向Json的String类型赋值
 * */
#define S2J_setString(json,stru,element) SetValueString(json,#element,(stru)->element)  
/**
 * Function:J2S_getString
 * Description:Json向Struct中的String类型赋值
 * */
#define J2S_getString(json,stru,element) {char *item=NULL; item = GetValueString(json,#element); if(item!=NULL){strcpy((stru)->element,item);}}
/**
 * Function:J2S_getInt
 * Description:Json向Struct中的Int类型赋值
 * */
#define J2S_getInt(json,stru,element) (stru)->element = GetValueInt(json,#element)
/**
 * Function:GetArrayValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中获取ArrayItem内容
 */
extern int GetArrayValueString(cJSON* json,int id, char* name, char* param);
/**
 * Function:GetValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中读取字符串内容
 */
extern char* GetValueString(cJSON* json,char* name);
/**
 * Function:GetValueInt
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 从json中读取int类型值
 */
extern int GetValueInt(cJSON* json,char* name);
/**
 * Function:SetValueString
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 向json中的String类型字段赋值
 */
extern int SetValueString(cJSON* json,char* name,char* value);
/**
 * Function:SetValueInt
 * Data:2021-11-11
 * Author:yangyongzhen
 * Description: 向json中的Int类型字段赋值
 */
extern int SetValueInt(cJSON* json,char* name,int value);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif


使用方法举例:


#include "jsonopt.h"
static cJSON* root;
PosStatus posStatus;
/**
从json文件中加载信息到结构体
*/
int LoadStatus(PosStatus *status){
  printf("LoadStatus ENTER\n");
  root = GetJsonObject(STATUS_FILE_NAME);
  char * out = cJSON_Print(root);
  printf("LoadStatus:json=%s\n",out);
    if(out == NULL){
        printf("LoadStatus error,no json data\n");
        return -1;
    }
  J2S_getString(root,status,sn);
  printf("[item] = %s\n",status->sn);
    J2S_getString(root,status,posno);
  printf("[item] = %s\n",status->posno);
  J2S_getString(root,status,city);
  printf("[item] = %s\n",status->city);
  J2S_getString(root,status,tyid);
  printf("[item] = %s\n",status->tyid);
  J2S_getString(root,status,sver);
  printf("[item] = %s\n",status->sver);
  J2S_getString(root,status,ctime);
  printf("[item] = %s\n",status->ctime);
    //item = GetValueString(root,"posno");
    //if(item != NULL){
    //    strcpy(status->posno,item);
    //    printf("[item] = %s\n",status->posno);
    //}
  return 0;
}
/**
结构体信息保存为json文件
*/
int SaveStatus(PosStatus status){
  char * out = NULL;
    printf("SaveStatus ENTER\n");
  if(root == NULL){
    printf("SaveStatus error\n");
    return -1;
  }
  S2J_setString(root,&status,sn);
  S2J_setString(root,&status,posno);
  S2J_setString(root,&status,tyid);
  S2J_setString(root,&status,city);
  S2J_setString(root,&status,sver);
  S2J_setInt(root,&status,unum1);
  S2J_setInt(root,&status,unum2);
  S2J_setInt(root,&status,amount);
  S2J_setInt(root,&status,count);
  S2J_setInt(root,&status,line);
  S2J_setString(root,&status,carno);
  S2J_setString(root,&status,jd);
  S2J_setString(root,&status,wd);
  S2J_setInt(root,&status,alarm);
  S2J_setInt(root,&status,pver);
  S2J_setInt(root,&status,bver);
  S2J_setString(root,&status,empid);
  S2J_setString(root,&status,rvs1);
  S2J_setString(root,&status,rvs2);
  S2J_setString(root,&status,stime);
  S2J_setString(root,&status,ctime);
  S2J_setInt(root,&status,tenant);
  //SetValueString(root,"carno",status.carno);
  //SetValueString(root,"jd",status.jd);
  //SetValueString(root,"wd",status.wd);
  printf("SaveStatus end\n");
  out = cJSON_Print(root);
  writeFile(STATUS_FILE_NAME,out);
  printf("SetStatus:json=%s\n",out);
  return 0;
}


//status.h头文件
#ifndef _STATUS_H_
#define _STATUS_H_
#include  "cJSON/cJSON.h"
//保存位置 终端状态监控文件存储位置
#define STATUS_FILE_NAME  "../opt/status.json"
//#define STATUS_FILE_NAME  "./status.json"
//终端设备状态信息
typedef struct _PosStatus{
  char sn[32];     //设备唯一号
    char posno[16];  //终端编号
    char city[10];   //城市代码
    char tyid[10];   //终端类型
    char sver[32];   //终端版本号
    int  unum1;      //未传记录数量--公交
    int  unum2;      //未传记录数量--三方
    char ndate[16];  //当前日期
    char ntime[16];  //当前时间
    int  amount;     //当班总额
    int  count;      //当班人数
    int  line;       //线路号
    char carno[16];  //车辆编号
    char jd[20];     //经度
    char wd[20];     //维度
    int  alarm;      //设备报警码
    char stime[16];  //开机时间
    char ctime[16];  //关机时间
    int  tenant;     //租户ID
}PosStatus;
extern PosStatus posStatus;
extern int LoadStatus(PosStatus *status);
extern int SaveStatus(PosStatus status);
extern int SetValueInt(cJSON* root,char* name,int value);
extern int SetValueString(cJSON* root,char* name,char* value);
extern char* GetValueString(cJSON* json,char* name);
extern int GetValueInt(cJSON* json,char* name);
extern cJSON* GetJsonObject(char* fileName);
extern int writeFile(char *filename,char *data);
#endif


static.c文件内容:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "status.h"
static cJSON* root;
PosStatus posStatus;
/**
从文件中读取json信息到结构体
*/
int LoadStatus(PosStatus *status){
  root = GetJsonObject(STATUS_FILE_NAME);
  char * out = cJSON_Print(root);
  printf("LoadStatus:json=%s\n",out);
    if(out == NULL){
        printf("LoadStatus error,no json data\n");
        return -1;
    }
    char * item = NULL;
    item = GetValueString(root,"sn");
    if(item != NULL){
        strcpy(status->sn,item);
        printf("[item] = %s\n",status->sn);
    }
    item = GetValueString(root,"posno");
    if(item != NULL){
        strcpy(status->posno,item);
        printf("[item] = %s\n",status->posno);
    }
    item = GetValueString(root,"city");
    if(item != NULL){
        strcpy(status->city,item);
        printf("[item] = %s\n",status->city);
    }
    item = GetValueString(root,"tyid");
    if(item != NULL){
        strcpy(status->tyid,item);
        printf("[item] = %s\n",status->tyid);
    }
    item = GetValueString(root,"sver");
    if(item != NULL){
        strcpy(status->sver,item);
        printf("[item] = %s\n",status->sver);
    }
  return 0;
}
/**
结构体信息写入json文件
*/
int SaveStatus(PosStatus status){
  char * out = NULL;
    printf("SaveStatus ENTER\n");
  if(root == NULL){
    printf("SaveStatus error\n");
    return -1;
  }
    SetValueString(root,"sn",status.sn);
    SetValueString(root,"posno",status.posno);
    SetValueString(root,"tyid",status.tyid);
  SetValueString(root,"city",status.city);
    SetValueString(root,"sver",status.sver);
  SetValueInt(root,"unum1",status.unum1);
    SetValueInt(root,"unum2",status.unum2);
    SetValueInt(root,"amount",status.amount);
    SetValueInt(root,"count",status.count);
    SetValueInt(root,"line",status.line);
  SetValueString(root,"carno",status.carno);
    SetValueString(root,"jd",status.jd);
    SetValueString(root,"wd",status.wd);
    SetValueInt(root,"alarm",status.alarm);
    SetValueString(root,"stime",status.stime);
    SetValueString(root,"ctime",status.ctime);
    SetValueInt(root,"tenant",status.tenant);
  out = cJSON_Print(root);
  writeFile(STATUS_FILE_NAME,out);
  printf("SetStatus:json=%s\n",out);
  return 0;
}
int writeFile(char *filename,char *data){
  FILE *fp = NULL;
  fp = fopen(filename,"w+");
  if(fp == NULL){
    fprintf(stderr,"open file failed\n");
    return -1;
  }
  fprintf(fp,"%s",data);
  if(fp != NULL){
    fclose(fp);
  }
  return 0;
}
cJSON* GetJsonObject(char* fileName){
    long len;
    char* pContent;
    int tmp;
    cJSON* json;
    FILE* fp = fopen(fileName, "rb+");
    if(!fp){
        printf("open file error\n");
        return NULL;
    }
    printf("open file success\n");
    fseek(fp,0,SEEK_END);
    len=ftell(fp);
    if(0 == len){
        printf("file len is 0\n");
        return NULL;
    }
    fseek(fp,0,SEEK_SET);
    pContent = (char*) malloc (sizeof(char)*len);
    tmp = fread(pContent,1,len,fp);
    fclose(fp);
    json = cJSON_Parse(pContent);
    if (!json)
    {
        free(pContent);
        return NULL;
    }
    free(pContent);
    printf("read file ok\n");
    return json;
}
//读取cJSON索引为index的结点某个key值对应的value,索引从0开始
int GetArrayValueString(cJSON* json,int id, char* name, char* param){
    cJSON* node;
    node = cJSON_GetArrayItem(json,id);
    if(!node){
        return -1;
    }
    sprintf(param, "%s", cJSON_GetObjectItem(node, name)->valuestring);
    return 0 ;
}
char* GetValueString(cJSON* json,char* name){
  cJSON* pObj = NULL;
    pObj = cJSON_GetObjectItem(json,name);
    if(pObj != NULL){
      return pObj->valuestring;
    }else{
      return NULL;
    }
}
int GetValueInt(cJSON* json,char* name){
  cJSON* pObj = NULL;
    pObj = cJSON_GetObjectItem(json,name);
    if(pObj != NULL){
      return pObj->valueint;
    }else{
      return 0;
    }
}
int SetValueString(cJSON* json,char* name,char* value){
  strcpy(cJSON_GetObjectItem(json,name)->valuestring,value);
  return 0;
}
int SetValueInt(cJSON* json,char* name,int value){
  cJSON_GetObjectItem(json,name)->valueint = value;
  cJSON_GetObjectItem(json,name)->valuedouble = value;
  return 0;
}
/*
int main(){
  printf("cjson test,read and save\n");
  LoadStatus(&posStatus);
    strcpy(posStatus.sver,"NC_B503_YYZ");
    posStatus.alarm = 6;
    posStatus.amount = 10;
    posStatus.count = 12;
    strcpy(posStatus.posno,"413101010E");
  SaveStatus(posStatus);
}
*/


生成的json文件如:


{
  "sn": "00a0c6000023",
  "posno":"413101010E",
  "city": "",
  "tyid": "",
  "sver": "NC_B503_YYZ",
  "unum1":  0,
  "unum2":  0,
  "ndate":  "2021-08-11",
  "ntime":  "17:20:30",
  "amount": 10,
  "count":  12,
  "line": 0,
  "carno":  "",
  "jd": "",
  "wd": "",
  "alarm":  6,
  "stime":  "",
  "ctime":  "",
  "tenant": 0
}


附带一个终端开机自启动脚本startmonitor.sh:


#!/bin/bash
fileName="/app/city_app/opt/monitor"
buzzGPIO="/sys/class/gpio/gpio15"
#enable buzzse for notifying success
function beep_notify()
{
   if [ ! -d "$buzzGPIO" ]; then
        echo 15 > /sys/class/gpio/export
   fi
   if [ -d "$buzzGPIO" ]; then
        echo "out" > "/sys/class/gpio/gpio15/direction"
        echo "1" > "/sys/class/gpio/gpio15/value"
        sleep 1
        echo "0" > "/sys/class/gpio/gpio15/value"
   fi
}
function CheckProcess()
{
  PROCESS_NUM=`ps | grep "$1" | grep -v "grep" | wc -l`
  return $PROCESS_NUM
}
if [ ! -f $fileName ]; then  
      echo "error!monitor file not exit!"
        exit 1
    else 
  echo "find monitor file,begin start..."
    CheckProcess qrlinux
    if [ $? -eq 0 ];then
    echo "no monitor progress find!"
    else
    echo "find monitor,..."
      killall -9 monitor
        sleep 1
        fi 
        cd /app/city_app/opt/
      ./monitor -monitorcfg=./monitorcfg.ini &  
      echo "start ok"
      beep_notify
      exit 0
fi


终端开机自启动服务应用的方法:


system("killall -9 monitor");
 system("../opt/startmonitor.sh");
相关文章
|
17天前
|
监控 前端开发 数据可视化
Github 12.3kstar, 3分钟起步做中后台?Go+Vue 脚手架,把权限、代码生成、RBAC 都封装好了
Go-admin 是基于 Gin + Vue 的中后台脚手架,集成 Casbin RBAC 权限、JWT 鉴权、GORM 数据库操作与 Swagger 文档,内置用户、角色、菜单等管理模块。提供代码生成器与表单构建器,支持多租户与多前端框架(Element UI/Arco/Ant Design),3 分钟快速搭建企业级后台,助力高效交付。
|
8月前
|
编译器 Go
揭秘 Go 语言中空结构体的强大用法
Go 语言中的空结构体 `struct{}` 不包含任何字段,不占用内存空间。它在实际编程中有多种典型用法:1) 结合 map 实现集合(set)类型;2) 与 channel 搭配用于信号通知;3) 申请超大容量的 Slice 和 Array 以节省内存;4) 作为接口实现时明确表示不关注值。此外,需要注意的是,空结构体作为字段时可能会因内存对齐原因占用额外空间。建议将空结构体放在外层结构体的第一个字段以优化内存使用。
|
5月前
|
JSON Go C语言
Go语言之定义结构体(Struct)-《Go语言实战指南》
Go 语言中的结构体(`struct`)是一种复合数据类型,可将多个不同类型的字段组合成一个类型。本文介绍了结构体的基本定义、实例创建方式、字段访问与修改、零值特性、比较规则、嵌套使用及标签功能。通过示例代码详细讲解了如何定义和操作结构体,以及其在 JSON 编码等场景的应用。
|
5月前
|
JSON JavaScript 前端开发
Go语言JSON 序列化与反序列化 -《Go语言实战指南》
本文介绍了 Go 语言中使用 `encoding/json` 包实现 JSON 与数据结构之间的转换。内容涵盖序列化(`Marshal`)和反序列化(`Unmarshal`),包括基本示例、结构体字段标签的使用、控制字段行为的标签(如 `omitempty` 和 `-`)、处理 `map` 和切片、嵌套结构体序列化、反序列化未知结构(使用 `map[string]interface{}`)以及 JSON 数组的解析。最后通过表格总结了序列化与反序列化的方法及类型要求,帮助开发者快速掌握 JSON 数据处理技巧。
|
10月前
|
程序员 Go
go语言中结构体(Struct)
go语言中结构体(Struct)
285 71
|
11月前
|
存储 Rust Go
Go nil 空结构体 空接口有什么区别?
本文介绍了Go语言中的`nil`、空结构体和空接口的区别。`nil`是预定义的零值变量,适用于指针、管道等类型;空结构体大小为0,多个空结构体实例指向同一地址;空接口由`_type`和`data`字段组成,仅当两者均为`nil`时,空接口才为`nil`。
227 1
Go nil 空结构体 空接口有什么区别?
|
11月前
|
编译器 Go
探索 Go 语言中的内存对齐:为什么结构体大小会有所不同?
在 Go 语言中,内存对齐是优化内存访问速度的重要概念。通过调整数据在内存中的位置,编译器确保不同类型的数据能够高效访问。本文通过示例代码展示了两个结构体 `A` 和 `B`,尽管字段相同但排列不同,导致内存占用分别为 40 字节和 48 字节。通过分析内存布局,解释了内存对齐的原因,并提供了优化结构体字段顺序的方法,以减少内存填充,提高性能。
124 3
Go to Learn Go之结构体
Go to Learn Go之结构体
95 5
|
存储 Shell Go
Go语言结构体和元组全面解析
Go语言结构体和元组全面解析
Go: struct 结构体类型和指针【学习笔记记录】
本文是Go语言中struct结构体类型和指针的学习笔记,包括结构体的定义、成员访问、使用匿名字段,以及指针变量的声明使用、指针数组定义使用和函数传参修改值的方法。