C++-cjson的读写与个人理解.md

cJSON的读写与个人理解

[TOC]

写cJSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
## 输出到文件流 即从内存到硬盘
@fileName 文件路径
@ std::ios::out | std::ios::trunc 打开文件的方式
@ 这些标识符可以被组合使用,中间以”或”操作符(|)间隔。
*/
std::ofstream ofs(fileName.toLocal8Bit().constData(), std::ios::out | std::ios::trunc);
if (!ofs.good())
return;


/*
@ jsonObj 这个cJSON一定要完全同名,原因是cJSON的宏要直接引用它,具体可以查看头文件的宏定义
*/
std::shared_ptr<cJSON> idx(cJSON_CreateObject(), cJSON_Delete);
cJSON* jsonObj = idx.get();


/*
@ v 变量名 最后保存到cJSON时将成为 字段名即key
@ 实际上cJson的数据存储方式可以理解为多层次()嵌套的键值对的集合 <key,value(<key,value>,<key,value>)>
*/
//double型 int string bool同理
double *v=0.01;
JSON_DOUBL_SET(v);


//double 数组 其他同理
double *array = array[n];
JSON_DOUBLEARRAY_SET(array, n);


/*
## 字符串列表 其他类型的List同理
## 只需将cJSON_CreateString 换成同作用的函数
@ yourList 为QStringList
*/
cJSON *List = cJSON_CreateArray();
for (const QString str : yourList)
{
QByteArray strArr = str.toLocal8Bit();
cJSON_AddItemToArray(List, cJSON_CreateString(std::string(strArr.constData(), strArr.length()).c_str()));
}
cJSON_AddItemToObject(jsonObj, "List", List);

//完成cJSON对象后,将jsonObj的内容转换成char*,输出到文件

char* idx_txt = cJSON_Print(jsonObj);
ofs << idx_txt;

ofs.close();
free(idx_txt);

cJSON读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
@idx_input 暂存cJSON文件的内容,即从硬盘到内存
@len cJSON文件的内容的大小
@至于为什么要 多存一个 '\0',我理解为cJSON的结束符(未经证实,纯属猜测)
*/
std::vector<char> idx_input;
qint64 len = QFileInfo(fileName).size();
idx_input.resize(len + 1);
std::ifstream ifs(fileName.toLocal8Bit().constData(), std::ios::in);
if (!ifs.good())
return;
ifs.read(&(idx_input.front()), len);
idx_input.back() = '\0';
ifs.close();

std::shared_ptr<cJSON> idx(cJSON_Parse(&(idx_input.front())), cJSON_Delete);
cJSON* jsonObj = idx.get();
if (!jsonObj)
return;
//读key为v的vlue int bool double string同理
cJSON* v = cJSON_GetObjectItem(jsonObj, "v");
if (v)
yourV = v->valueint);
else
return false;
//也可以
int v=0;
JSON_INT_GET(v);


/*
## 数组 list 读取方式类似
@ List 从父对象jsonObj里找到key为"List"的键值对的地址赋值给List
@ tmp的父对象为List,从父对象List里找到第i个键值对的地址赋值给tmp
@ tmp->valuestring 取tmp的value
*/
cJSON* List = cJSON_GetObjectItem(jsonObj, "List");
if (List)
{
for (int i = 0; i < cJSON_GetArraySize(List); i++)
{
cJSON *tmp = cJSON_GetArrayItem(List, i);
yourList.append(QString::fromLocal8Bit(tmp->valuestring));
}
}
else
return;

更复杂的数据结构请参考

https://blog.csdn.net/QiHsMing/article/details/94671262?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase


C++-cjson的读写与个人理解.md
http://pla.com/2021/04/01/C++-cjson的读写与个人理解/
作者
RenMingchang
发布于
2021年4月1日
许可协议