C++ JSON

目录

[TOC]

安装(Windows)

1、下载 : https://codeload.github.com/open-source-parsers/jsoncpp/zip/refs/tags/1.9.3

2、VSCode 打开项目,直接Cmake编译项目

3、得到libjsoncpp.a文件

4、新建项目就可以使用json了

项目配置

VS 项目配置g++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"label": "build demo_json",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${workspaceFolder}/demo_json.cpp",
// "-I", "D:/Tools/cplus_relate/eigen-3.4.0/Eigen/",
"-I", "${workspaceFolder}/include/",
"-L", "${workspaceFolder}/libs/",
"-l", "jsoncpp",
"-o", "main.exe",
],
"group": {
"kind": "build",
"isDefault": true
},
"dependsOn":[
"clear",
],
},

CMake 配置

使用

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 int ReadJson(const std::string & strValue) 
{
using namespace std;

Json::Reader reader;
Json::Value value;

if (reader.parse(strValue, value))
{
//解析json中的对象
string out = value["name"].asString();
cout << "name : " << out << endl;
cout << "number : " << value["number"].asInt() << endl;
cout << "value : " << value["value"].asBool() << endl;
cout << "no such num : " << value["haha"].asInt() << endl;
cout << "no such str : " << value["hehe"].asString() << endl;

//解析数组对象
const Json::Value arrayNum = value["arrnum"];
for (unsigned int i = 0; i < arrayNum.size(); i++)
{
cout << "arrnum[" << i << "] = " << arrayNum[i];
}
//解析对象数组对象
Json::Value arrayObj = value["array"];
cout << "array size = " << arrayObj.size() << endl;
for(unsigned int i = 0; i < arrayObj.size(); i++)
{
cout << arrayObj[i];
}
//从对象数组中找到想要的对象
for(unsigned int i = 0; i < arrayObj.size(); i++)
{
if (arrayObj[i].isMember("string"))
{
out = arrayObj[i]["string"].asString();
std::cout << "string : " << out << std::endl;
}
}
}

return 0;
}

std::string writeJson()
{
using namespace std;

Json::Value root;
Json::Value arrayObj;
Json::Value item;
Json::Value iNum;

item["string"] = "this is a string";
item["number"] = 999;
item["aaaaaa"] = "bbbbbb";
arrayObj.append(item);

//直接对jsoncpp对象以数字索引作为下标进行赋值,则自动作为数组
iNum[1] = 1;
iNum[2] = 2;
iNum[3] = 3;
iNum[4] = 4;
iNum[5] = 5;
iNum[6] = 6;

//增加对象数组
root["array"] = arrayObj;
//增加字符串
root["name"] = "json";
//增加数字
root["number"] = 666;
//增加布尔变量
root["value"] = true;
//增加数字数组
root["arrnum"] = iNum;

root.toStyledString();
string out = root.toStyledString();

return out;
}
// ref:: http://t.zoukankan.com/fengbohello-p-4066254.html

配置

VScode 配置 svn_LDG1998的博客-CSDN博客_vscode配置svn