CSON使用實(shí)例
聲明結(jié)構(gòu)體:
/** 項(xiàng)目結(jié)構(gòu)體 */
struct project
{
int id;
char *name;
};
/** 倉(cāng)庫(kù)結(jié)構(gòu)體 */
struct hub
{
int id;
char *user;
struct project *cson;
};
定義數(shù)據(jù)模型:
對(duì)每一個(gè)需要使用cson的結(jié)構(gòu)體,都需要定義相對(duì)應(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),
};
/** 倉(cāng)庫(kù)結(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);
/** 序列化對(duì)象 */
char *formatJson = csonEncodeFormatted(pHub, hubModel, sizeof(hubModel)/sizeof(CsonModel));
printf("format json: %srn", formatJson);
/** 釋放結(jié)構(gòu)體對(duì)象 */
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"
}
}
可以看到,無(wú)論是解析json,還是序列化結(jié)構(gòu)體到j(luò)son,在使用CSON的情況下,都只需要一行代碼就可以解決,同樣的操作,在使用原生cJSON的情況下,你可能需要多次判斷,解析元素。
-
數(shù)據(jù)
+關(guān)注
關(guān)注
8文章
7233瀏覽量
90786 -
C語(yǔ)言
+關(guān)注
關(guān)注
180文章
7628瀏覽量
139822 -
模型
+關(guān)注
關(guān)注
1文章
3469瀏覽量
49843 -
結(jié)構(gòu)體
+關(guān)注
關(guān)注
1文章
130瀏覽量
11008
發(fā)布評(píng)論請(qǐng)先 登錄
基于面向?qū)ο?b class='flag-5'>數(shù)據(jù)模型的信息管理系統(tǒng)
什么是層次數(shù)據(jù)模型、數(shù)據(jù)流量分析
什么是ActiveDirectory數(shù)據(jù)模型、數(shù)字數(shù)據(jù)網(wǎng)絡(luò)
數(shù)據(jù)模型概念及類(lèi)型劃分
概率XML數(shù)據(jù)模型的綜述

共享系統(tǒng)數(shù)據(jù)模型

Cassandra數(shù)據(jù)模型設(shè)計(jì)指南
Google Dremel數(shù)據(jù)模型講解

數(shù)據(jù)模型的概念和作用
數(shù)據(jù)模型的三要素
數(shù)據(jù)模型有哪些種類(lèi)
智能電網(wǎng)的數(shù)據(jù)模型標(biāo)準(zhǔn)
詳談Python的數(shù)據(jù)模型和對(duì)象模型

評(píng)論