cJSON 使用记录——封装

由于网上大多都是cJSON解析的,但是封装的却很少,所以这里将我的封装方法记录下来。

cJSON是轻量级的库,仅有一个cJSON.h和一个cJSON.cpp,使用时候直接导入就行,俩字儿,方便!!

基本函数主要有:(常用的打"!")

! cJSON *  cJSON_CreateObject(void);

! void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);

cJSON *  cJSON_CreateNull(void);

cJSON *  cJSON_CreateTrue(void); 

cJSON *  cJSON_CreateFalse(void);

cJSON *  cJSON_CreateBool(int b);

! cJSON *  cJSON_CreateNumber(double num);

! cJSON *  cJSON_CreateString(const char *string);

! cJSON * cJSON_CreateArray(void);

! cJSON * cJSON_CreateObject(void);

封装时,感觉和xml文件有点像。。。

个人小记:

添加到Object时,需要对应的属性名;

添加到Array时可要,可不要;

封装二维数组时,可以在array里面添加array;

example:

#include <iostream>
#include <vector>
#include "cJSON.h"

using namespace std;

struct Property{
double position[3];
double orientation[3];
};

struct ObjectsInfo{
char* id;
vector<property></property> properties;
};

struct ObjectInfo{
char* id;
Property property;
};

char* encodeInfo(ObjectInfo objInfo){
	cJSON* item;
	
	//创建节点
	cJSON* root = cJSON_CreateObject();
	cJSON_AddStringToObject(root,"ID",objInfo.id);

	//创建子节点
	cJSON* properties = cJSON_CreateObject();
	cJSON_AddItemToObject(root,"Properties",properties);

	cJSON* position = cJSON_CreateArray();
	cJSON* orientation = cJSON_CreateArray();
	for(int i =0;i&lt;3;i++){
		cJSON_AddItemToArray(position, cJSON_CreateNumber(objInfo.property.position[i]));
		cJSON_AddItemToArray(orientation, cJSON_CreateNumber(objInfo.property.orientation[i]));
		
	}
	cJSON_AddItemToObject(properties,"Position",position);
	cJSON_AddItemToObject(properties,"Orientation",orientation);
	
	
	

	char* string = cJSON_Print(root);

	return string;

}

int main(){
	ObjectInfo objInfo;
	objInfo.id = "CoffeeCup";
	char* str= encodeInfo(objInfo);
    cout<<str<<endl;

    return 0;
}

参考链接:

https://www.zybuluo.com/armink/note/189711

https://my.oschina.net/u/2255341/blog/543508

https://www.jianshu.com/p/5d999b2e8cfa

tips:根据工程的需要,用完后请记得

cJSON_Delete(root); //!!!!!!it`s important!否则的话会有内存泄漏的问题

解析的话,比较简单,直接getObject就行了

cJSON_GetObjectItem();
cJSON_GetArraySize();
cJSON_GetArrayItem();



example:
cJSON *MAC_arry     = cJSON_GetObjectItem( clientlist, "Maclist");
if( MAC_arry != NULL ){
    int  array_size   = cJSON_GetArraySize ( MAC_arry );

    for( iCnt = 0 ; iCnt < array_size ; iCnt ++ ){
        cJSON * pSub = cJSON_GetArrayItem(MAC_arry, iCnt);
        if(NULL == pSub ){ continue ; }

        char * ivalue = pSub->valuestring ;
        printf("Maclist[%d] : %s",iCnt,ivalue);
    }
}

猜你喜欢

转载自blog.csdn.net/hehehetanchaow/article/details/84638147