upu_struct.h封装了有关 pMtInfo结构体的内容,用到的部分如下图所示:
利用jansson库实现将传入结构体 pMtInfo 中包含的数据内容转换成 JSON 字符串返回
代码如下:
#include <stdio.h> #include <string.h> #include "jansson.h" #include "upu_struct.h" #include "upu_proto_parse.h" // pMtInfo -> 传入 mtinfo 结构的首地址 // nNum -> 传入 mtinfo 结构的数量 // pLen -> C 结构转换成 JSON 结构字符串后的长度 // 实现功能: // 将传入结构体 pMtInfo 中包含的数据内容转换成 JSON 字符串返回 char* struct_to_json_n( mtinfo *pMtInfo, int nNum, int *pLen ) { json_t *object,*array; int i,size; array=json_array(); for(i=0;i<nNum;++i) { object=json_object(); //结构体 pMtInfo 中包含的数据内容 const char *pMoid=mt_get_moid(&pMtInfo[i]); const char* pE164=mt_get_e164(&pMtInfo[i]); const char* pPrototype=mt_get_prototype(&pMtInfo[i]); const char* pMttype=mt_get_mttype(&pMtInfo[i]); const char* pMtstate=mt_get_mtstate(&pMtInfo[i]); const char* pMtip=mt_get_mtip(&pMtInfo[i]); const char* pNuip=mt_get_nuip(&pMtInfo[i]); const char* pUserdomain=mt_get_userdomain(&pMtInfo[i]); const char* pDevid=mt_get_devid(&pMtInfo[i]); //将结构体 pMtInfo 中包含的数据内容转换为json格式 json_t *pJsonMoid=json_string(pMoid); json_t *pJsonE164=json_string(pE164); json_t *pJsonPrototype=json_string(pPrototype); json_t *pJsonMttype=json_string(pMttype); json_t *pJsonMtstate=json_string(pMtstate); json_t *pJsonMtip=json_string(pMtip); json_t *pJsonNuip=json_string(pNuip); json_t *pJsonUserdomain=json_string(pUserdomain); json_t *pJsonDevid=json_string(pDevid); //将json结构的内容整合为object json_object_set_new(object, "Moid", pJsonMoid); json_object_set_new(object, "E164", pJsonE164); json_object_set_new(object, "Prototype", pJsonPrototype); json_object_set_new(object, "Mttype", pJsonMttype); json_object_set_new(object, "Mtstate", pJsonMtstate); json_object_set_new(object, "Mtip", pJsonMtip); json_object_set_new(object, "Nuip", pJsonNuip); json_object_set_new(object, "Userdomain", pJsonUserdomain); json_object_set_new(object, "Devid", pJsonDevid); int size1=json_object_size(object); printf("[%d]:size1=%d\n",i,size1); //将本结构体数组转化为json格式的字符串 char *CurResult=NULL; CurResult=json_dumps(object, JSON_PRESERVE_ORDER); printf("CurResult=%s\n",CurResult); //将本字符串添加到json结构体数组中 json_array_insert_new(array,i,object); } size=json_array_size(array); printf("size=%d\n",size); char *result=json_dumps(array,JSON_PRESERVE_ORDER); return result; } int main() { int i = 0; int nLen = 0; int nNum = 5; char *pJsonToString=NULL; mtinfo *pMtInfoArray = NULL; pMtInfoArray = (mtinfo *)malloc( nNum * sizeof(mtinfo) ); memset( pMtInfoArray, 0, nNum * sizeof(mtinfo) ); // 通过函数 mt_set_e164 设置 E164 号 0512111885621 ~ 0512111885625 到结构 pMtInfoArray[n] 中 mt_set_e164(&pMtInfoArray[0],"0512111885621"); mt_set_e164(&pMtInfoArray[1],"0512111885622"); mt_set_e164(&pMtInfoArray[2],"0512111885623"); mt_set_e164(&pMtInfoArray[3],"0512111885624"); mt_set_e164(&pMtInfoArray[4],"0512111885625"); pJsonToString=struct_to_json_n( pMtInfoArray, nNum, &nLen ); printf("pJsonTosTring=%s\n",pJsonToString); return 0; }