记录在使用C++的过程中的一些代码实现。

C++二维数组解析Json对象数组(旧方法)

JSON文件

example.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"type":"HJ212-2017",
"cycle":60,
"host":"192.168.101.114",
"port":5095,
"mn":"12345678",
"st":"12",
"cn":"34",
"pw":"56",
"cp":
[
{"n":"abc","dt":"4N.0","ds":"LB33","len":1,"group":"1"},
{"n":"bcd","dt":"C2.0","ds":"LB0","len":1,"group":"2"},
{"n":"cde","dt":"YYYY0.0","ds":"LB11","len":4,"group":"3"},
{"n":"qwexxx","dt":"N2.3","ds":"LW78","len":13,"group":"4"},
{"n":"qwettt","dt":"YYYY0.0","ds":"LW5","len":123,"group":"4"}
]
}

JSON结构体

struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
typedef struct {
string n_; ///< Instruction parameter field name.
string dt_; ///< Instruction parameter data type and integer bit and decimal places.
string ds_; ///< Instruction parameter data source.
uint32_t len_; ///< Instruction parameter ?.
string group_; ///< Instruction parameter group.
} JSON_CHA_D;

typedef struct {
string type_; ///< Support protocol type.
uint32_t cycle_; ///< The cycle to reported data.
string host_; ///< The reported data of server address.
int port_; ///< The reporeted data of server port.

string mn_; ///< Equipment number(MN).
string st_; ///< System coding(ST).
string cn_; ///< Command code(CN).
string pw_; ///< Access password(PW).
} JSON_STA_D;

处理JSON对象数组到二维数组

GetJsonApi
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
#include <jsoncpp/json/json.h>

int Hj212Service::GetJson(void)
{
char path[256];
strcpy(path, "./example.json", 14);
string json_file_path_ = path;
JSON_STA_D *pjs_sta = new JSON_STA_D;
this->GetJsonSta(json_file_path_, pjs_sta);

int len;
this->GetJsonChaLen(json_file_path_, &len);
JSON_CHA_D **pjs_cha = new JSON_CHA_D *[len];

for (int i = 0; i < len; i++) {
pjs_cha[i] = new JSON_CHA_D;
}

-----------------------------------------------------------------------------------------------
/*** How to Get the json object logic to A two-dimensional array. ***/
-----------------------------------------------------------------------------------------------
// Get json arry object.
ifstream ifs(json_file_path_.c_str());
Json::Reader reader;
Json::Value d;

// Judge json file is existed.
bool ret = reader.parse(ifs, d);
if (ret == false) {
printf("Parse ReadConfig() json data error.\n");
ifs.close();
return -1;
}
ifs.close();

// Get the json normal key.
js_d->type_ = d["type"].asString();
js_d->cycle_ = d["cycle"].asUInt();
js_d->host_ = d["host"].asString();
js_d->port_ = d["port"].asUInt();
js_d->mn_ = d["mn"].asString();
js_d->st_ = d["st"].asString();
js_d->cn_ = d["cn"].asString();
js_d->pw_ = d["pw"].asString();

// Parse json arrayObj.
const Json::Value arrayObj = d["cp"];
// Get directive parameter(cp) json data.
for (int i = 0; i < arrayObj.size(); i++) {
pjs_cha[i]->n_ = arrayObj[i]["n"].asString();
pjs_cha[i]->dt_ = arrayObj[i]["dt"].asString();
pjs_cha[i]->ds_ = arrayObj[i]["ds"].asString();
pjs_cha[i]->len_ = stoi(arrayObj[i]["len"].asString());
pjs_cha[i]->group_ = arrayObj[i]["group"].asString();
}

cout << pjs_sta->type_ << endl;
cout << pjs_sta->cycle_ << endl;
cout << pjs_sta->host_ << endl;
cout << pjs_sta->port_ << endl;
cout << pjs_sta->mn_ << endl;
cout << pjs_sta->st_ << endl;
cout << pjs_sta->cn_ << endl;

for (int i = 0; i < len; i++) {
cout << pjs_cha[i]->n_ << endl;
cout << pjs_cha[i]->dt_ << endl;
cout << pjs_cha[i]->ds_ << endl;
cout << pjs_cha[i]->len_ << endl;
cout << pjs_cha[i]->group_ << endl;
}

for (int i = 0; i < len; i++) {
delete pjs_cha[i];
}

delete pjs_sta;
delete[] pjs_cha;

return 0;
}

解析只有JSON对象的Json文件(旧方法)

JSON文件

test.json
1
2
3
4
5
[
{"a":"1", "b":"2", "c":"3"},
{"a":"4", "b":"5", "c":"6"},
{"a":"7", "b":"8", "c":"9"}
]

处理DEMO

demo.cpp
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
#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>

using namespace std;

int main()
{
/** Test.json content.
[
{"a":"1", "b":"2", "c":"3"},
{"a":"4", "b":"5", "c":"6"},
{"a":"7", "b":"8", "c":"9"}
]
*/
char path[256] = "./test.json";

// Get json arry object.
// ifstream param must be char array or char *.
string path_ = path;
ifstream ifs(path_.c_str());
// Follow is Errno using.
// ifstream ifs(path_);
Json::Reader reader;
// Parse json arrayObj.
Json::Value arrayObj;

// Judge json file is existed.
bool ret = reader.parse(ifs, arrayObj);
if (ret == false) {
std::cout << "Parse ReadConfig() json data error." << std::endl;
ifs.close();
return -1;
}
ifs.close();

// Get directive parameter(cp) json data.
for (int i = 0; i < arrayObj.size(); i++) {
std::cout << arrayObj[i]["a"].asString() << std::endl;
std::cout << arrayObj[i]["b"].asString() << std::endl;
std::cout << arrayObj[i]["c"].asString() << std::endl;
}

return 0;
}

创建JSON格式数据(旧方法)

构建JSON数据

demo.c
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
#include <iostream>
#include <jsoncpp/json/json.h>
#include <fstream>

using namespace std;

int main() {
// Create the characters array json object.
Json::Value ch;
ch[0]["name"] = "Jabberwock";
ch[0]["chapter"] = 1;
ch[1]["name"] = "Cheshire Cat";
ch[1]["chapter"] = 6;
ch[2]["name"] = "Mad Hatter";
ch[2]["chapter"] = 7;

// Create the json array not key.
Json::Value ary;
ary[0] = "Zhang san";
ary[1] = "Li shi";
ary[2] = "Xiao hong";
ary[3] = "Xiao ming";

// create the main object.
Json::Value val;
val["book"] = "Alice in Wonderland";
val["year"] = 1865;
val["win"] = true;
val["characters"] = ch;
val["name"] = ary;

// Output json ch.
cout << ch << '\n';

// Output json by closely.
Json::FastWriter out;
cout << out.write(val) << '\n';

// Output json by normal.
Json::StyledWriter out1;
cout << out1.write(val) << '\n';

// Output json to file.
ofstream fjson;
fjson.open("demo.json");
fjson << out1.write(val);
fjson.close();
}

正则JSON末尾的换行

regex.cpp
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
#include <boost/regex.hpp>
#include <iostream>
#include <string>

using namespace::boost;
using namespace::std;

void test(void)
{
// regex re("(https?://www.ttufo.com/.+/.+/.+)(_\\d+)(.html?)");
// string target("http://www.ttufo.com/ufo/201705/154053_3.html");
regex re("(.*)\\r\\n$");
string target("##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&1C80\r\n");
// NOTE: cmatch is meaning char *, smatch is string
cmatch what;
// smatch what;

if (regex_match(target.c_str(), what, re)) {
// if (regex_match(target, what, re)) {
cout << "match " << what.size() << endl;

for (int i = 0; i < what.size(); i++) {

cout << "what[" << i << "]: " << what[i] << endl;
}
} else {
cout << "not match " << endl;
}
}

int main(void)
{
test();
return 0;
}

消除FastJson末尾产生的换行

RemFastJsonLastNewline.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @brief Remove the Json::FastWriter transfer json string last \r\n symbol.
* @param[out] The need Remover \r\n symbol json string.
* @note The Api not long time test, maybe have bug.
*/
void RemFastJsonLastNewline(string *json_string)
{
// The follow code can erase string last symbol(blank_space\t\f\v\n\r).
// std::string whitespaces (" \t\f\v\n\r");
// FIXME: The implementation maybe have bug.
std::string whitespaces ("\n\r");
std::size_t found = json_string->find_last_not_of(whitespaces);
if (found != std::string::npos)
json_string->erase(found + 1);
else
json_string->clear();
}

解析未知格式的JsonApi

1.解析的json数据格式文件

file.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"book" : "Alice in Wonderland",
"year" : 1865,
"win" : true,
"result" : false,
"data" : [
{
"0x80000000":"12.5"
},
{
"0x80000001":"220"
},
{
"0x80000002":"80.5"
}
],
"name" : [ "Zhang san", "Li shi", "Xiao hong" ],
"string" : "Good Bye.",
"string.c_str" : "Good Bye."
}

2.解析json的示例代码(旧方法)

unpack_unknown_json.cpp
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>

using namespace std;

void unknow_json_traversal(Json::Value d)
{
// Jsoncpp function type() can judge 8 type is nullValue, intValue, uintValue,
// realValue, stringValue, booleanValue, arrayValue, objectValue.
// The json type detaile can visit http://jsoncpp.sourceforge.net/value_8h_source.html#l00036.
int cnt;
// Return a list of the member names.
Json::Value::Members mem = d.getMemberNames();
// Traversal json members by jsoncpp iterator.
for (Json::Value::Members::iterator iter = mem.begin(); iter != mem.end(); iter++) {
// The members of key.
cout << *iter << " : ";
// Judge the member value of type.
switch (d[*iter].type()) {
case Json::objectValue:
cout << endl;
// Recursion parse the json object.
unknow_json_traversal(d[*iter]);
break;
// When the member of type is jsonarray, it maybe array object or multiple array elements.
case Json::arrayValue:
cout << endl;
// Get the json array elements numbers.
cnt = d[*iter].size();
for (int i = 0; i < cnt; i++) {
switch (d[*iter][i].type()) {
// Recursion parse the json array object value of type.
case Json::objectValue:
unknow_json_traversal(d[*iter][i]);
break;
// Json array object type of value is string.
case Json::stringValue:
std::cout << d[*iter][i].asString() << std::endl;
break;
// Json array object type of value is float of double.
case Json::realValue:
std::cout << d[*iter][i].asDouble() << std::endl;
break;
// Json array object type of value is unsigned int.
case Json::uintValue:
std::cout << d[*iter][i].asUInt() << std::endl;
break;
// Json array object type of value is int.
case Json::intValue:
std::cout << d[*iter][i].asInt() << std::endl;
break;
}
}
break;
// Json member object type of value is string.
case Json::stringValue:
std::cout << d[*iter].asString() << std::endl;
break;
// Json member object type of value is float of double.
case Json::realValue:
std::cout << d[*iter].asDouble() << std::endl;
break;
// Json member object type of value is unsigned int.
case Json::uintValue:
std::cout << d[*iter].asUInt() << std::endl;
break;
// Json member object type of value is int.
case Json::intValue:
std::cout << d[*iter].asInt() << std::endl;
break;
// Json member object type of value is bool.
case Json::booleanValue:
std::cout << d[*iter].asBool() << std::endl;
// The asBool output value is 1 or 0.
if (d[*iter].asBool()) {
// If the asBool return 1 is true.
cout << "true" << endl;
} else {
// If the asBool return 0 is false.
cout << "false" << endl;
}
break;
// Json member object type of value is null.
case Json::nullValue:
return;
break;
}
}
return;
}

int main()
{
char path[256] = "./demo.json";

// Get json arry object.
// ifstream param must be char array or char *.
string path_ = path;
ifstream ifs(path_.c_str());
// Follow is Errno using.
// ifstream ifs(path_);
Json::Reader reader;
// Parse json arrayObj.
Json::Value arrayObj;

// Judge json file is existed.
bool ret = reader.parse(ifs, arrayObj);
if (ret == false) {
std::cout << "Parse ReadConfig() json data error." << std::endl;
ifs.close();
return -1;
}
ifs.close();

unknow_json_traversal(arrayObj);

return 0;
}

新Jsoncpp的使用(新方法)

创建Json

jsoncpp可能不支持中文输出而将中文转为unicode编码

Create.cpp
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
Json::Value root;
Json::Value sub;

root["name"] = "xiao hong";
root["age"] = 32;
root["school"] = "东大";

sub["name"] = "xiao ming";
sub["age"] = 33;
sub["school"] = "大阪";

root["man"] = sub;

Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = "";

// one way
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
std::ostringstream os;
writer->write(root, &os);
std::string str = os.str();
std::cout << str << std::endl;

// two way
Json::StreamWriterBuilder wbuilder;
// Configure the Builder, then ...
std::string outputConfig = Json::writeString(wbuilder, root);

解析Json

parse.cpp
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
//解析json文件

// one way
#include <fstream>

std::ifstream config_doc("config_doc.json", std::ifstream::binary);
config_doc >> root;

// two way
Json::Value root;
Json::CharReaderBuilder rbuilder;
// Configure the Builder, then ...
std::string errs;
bool parsingSuccessful = Json::parseFromStream(rbuilder, config_doc, &root, &errs);
if (!parsingSuccessful)
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse configuration\n"
<< errs;
return;
}

char strBuf[]="{ \"id\":666, \"name\":\"henryHe\"}";
std::istringstream iss(strBuf);
Json::Value readValue;
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
std::string errs;
bool parsingSuccessful = Json::parseFromStream(rbuilder, iss , &readValue, &errs);
if (!parsingSuccessful)
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse configuration\n"
<< errs;
return;
}
cout <<"id: "<< readValue["id"] << endl;
cout <<"name: "<< readValue["name"] << endl;

// 解析字符串
string sRecv = "{name = \"xiao hong\"}";
JSONCPP_STRING errs;
Json::Value root;
Json::CharReaderBuilder readerBuilder;
int res;

// 这一步可以一步判断json格式是否合法
std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
res = jsonReader->parse(sRecv.c_str(), sRecv.c_str() + sRecv.length(), &root, &errs);
if (!res || !errs.empty()) {
std::cout << "parseJson err. " << errs << std::endl;
return -1;
}

C++队列API

Queue Push Api

SetQueue.cpp
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
/**
* @brief Set substract size pack string to queue.
* @param[in] *send_pack_queue The save string queue.
* @param[in] int part_size The substract size.
* @param[in] int part_size The each substract size pack.
* @note
*/
void SetQueue(queue<string> *send_pack_queue, string *pack_string, int part_size)
{
// Judge the queue is empty.
if (!send_pack_queue->empty()) {
LOG(ERROR) << "The SetSendPackToQueue of Send subpack queue is not empty!";
// Empty the queue;
while (!send_pack_queue->empty()) {
send_pack_queue->pop();
}
}
int total_size = pack_string->size();

// Get the pack part number.
int pack_part_n = total_size / part_size + 1;

// Set the pack to queue.
string tmp_pack;
for (int i = 0; i < pack_part_n; i++) {
// When the substr size is more than residual value size, it can get residual value size.
if ( i == pack_part_n - 1) {
tmp_pack = pack_string->substr(0, pack_string->size());
send_pack_queue->push(tmp_pack);
break;
}
tmp_pack = pack_string->substr(0, part_size);
send_pack_queue->push(tmp_pack);
// When the last pack is not len as the part size the erase will segmentation fault.
pack_string->erase(pack_string->begin(), pack_string->begin() + part_size);
tmp_pack.clear();
}
}

Queue Pop

GetQueue Api

GetQueue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @brief Get string from queue.
* @param *send_pack_queue The save string queue.
* @param *send_pack_string The pop pack string.
*/
void GetQueue(queue<string> *send_pack_queue, string *send_pack_string)
{
// Judge the queue is empty.
if (send_pack_queue->empty()) {
LOG(ERROR) << "The GetSendPackToQueue of queue is empty.!";
return;
}

// Get the data from queue.
*send_pack_string = send_pack_queue->front();
send_pack_queue->pop();
}

完整取出Queue Demo

Demo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
string test_line = "1234567891011121314151617181920212223242526272829";
string test_line_ = test_line;
string show_str;
queue<string> t_q;

SetQueue(&t_q, &test_line_, 9);

string s_string;
while (!t_q.empty()) {
GetQueue(&t_q, &s_string);
cout << s_string.c_str() << " NUM:" << s_string.size() << endl;
}