CSON使用實(shí)例
聲明結(jié)構(gòu)體:
/** 項(xiàng)目結(jié)構(gòu)體 */
struct project
{
int id;
char *name;
};
/** 倉庫結(jié)構(gòu)體 */
struct hub
{
int id;
char *user;
struct project *cson;
};
定義數(shù)據(jù)模型:
對每一個需要使用cson的結(jié)構(gòu)體,都需要定義相對應(yīng)的數(shù)據(jù)模型
/** 項(xiàng)目結(jié)構(gòu)體數(shù)據(jù)模型 */
CsonModel projectModel[] =
{
CSON_MODEL_OBJ(struct project),
CSON_MODEL_INT(struct project, id),
CSON_MODEL_STRING(struct project, name),
};
/** 倉庫結(jié)構(gòu)體數(shù)據(jù)模型 */
CsonModel hubModel[] =
{
CSON_MODEL_OBJ(struct hub),
CSON_MODEL_INT(struct hub, id),
CSON_MODEL_STRING(struct hub, user),
CSON_MODEL_STRUCT(struct hub, cson, projectModel, sizeof(projectModel)/sizeof(CsonModel))
};
使用CSON解析:
只需要定義好數(shù)據(jù)模型,就可以使用CSON讀json進(jìn)行序列化和反序列化
void csonDemo(void)
{
char *jsonDemo = "{"id": 1, "user": "Letter", "cson": {"id": 2, "name": "cson"}}";
/** 解析json */
struct hub *pHub = csonDecode(jsonDemo, hubModel, sizeof(hubModel)/sizeof(CsonModel));
printf("hub: id: %d, user: %s, project id: %d, project name: %srn",
pHub- >id, pHub- >user, pHub- >cson- >id, pHub- >cson- >name);
/** 序列化對象 */
char *formatJson = csonEncodeFormatted(pHub, hubModel, sizeof(hubModel)/sizeof(CsonModel));
printf("format json: %srn", formatJson);
/** 釋放結(jié)構(gòu)體對象 */
csonFree(pHub, hubModel, sizeof(hubModel)/sizeof(CsonModel));
/** 釋放序列化生成的json字符串 */
csonFreeJson(formatJson);
}
運(yùn)行結(jié)果:
hub: id: 1, user: Letter, project id: 2, project name: cson
format json: {
"id": 1,
"user": "Letter",
"cson": {
"id": 2,
"name": "cson"
}
}
可以看到,無論是解析json,還是序列化結(jié)構(gòu)體到j(luò)son,在使用CSON的情況下,都只需要一行代碼就可以解決,同樣的操作,在使用原生cJSON的情況下,你可能需要多次判斷,解析元素。
-
數(shù)據(jù)
+關(guān)注
關(guān)注
8文章
7298瀏覽量
93575 -
C語言
+關(guān)注
關(guān)注
183文章
7634瀏覽量
144170 -
模型
+關(guān)注
關(guān)注
1文章
3618瀏覽量
51541 -
結(jié)構(gòu)體
+關(guān)注
關(guān)注
1文章
131瀏覽量
11268
發(fā)布評論請先 登錄
基于面向?qū)ο?b class='flag-5'>數(shù)據(jù)模型的信息管理系統(tǒng)
什么是層次數(shù)據(jù)模型、數(shù)據(jù)流量分析
什么是ActiveDirectory數(shù)據(jù)模型、數(shù)字數(shù)據(jù)網(wǎng)絡(luò)
數(shù)據(jù)模型概念及類型劃分
概率XML數(shù)據(jù)模型的綜述
共享系統(tǒng)數(shù)據(jù)模型
Cassandra數(shù)據(jù)模型設(shè)計(jì)指南
Google Dremel數(shù)據(jù)模型講解
數(shù)據(jù)模型的概念和作用
數(shù)據(jù)模型的三要素
數(shù)據(jù)模型有哪些種類
智能電網(wǎng)的數(shù)據(jù)模型標(biāo)準(zhǔn)
詳談Python的數(shù)據(jù)模型和對象模型

CSON使用實(shí)例:定義數(shù)據(jù)模型
評論