jsoncpp在linux下的配置
JSON 官方的解释为:JSON 是一种轻量级的数据传输格式。
关于 JSON 更具体的信息,可参见 JSON 官网:http://www.json.org。
jsoncpp 是比较出名的 C++ JSON 解析库。在 JSON 官网也是首推的。
下载地址为:http://sourceforge.net/projects/jsoncpp(版本为jsoncpp-src-0.5.0)。
下面开始说明配置方法:
1、先下载scons:(http://www.scons.org/)(版本为scons-2.1.0)并解压;
设定环境变量 # export MYSCONS=解压的路径
2、scons部署:进入scons解压目录(假定为$MYSCONS),执行python $MYSCONS/setup.py install将scons部署完毕。
3、使用scons编译jsoncpp(版本为jsoncpp-src-0.5.0)
进入jsoncpp解压目录,执行命令: # python $MYSCONS/script/scons.py platform=linux-gcc
将jsoncpp编译,在解压目录jsoncpp-src-0.5.0/libs/linux-gcc-3.4.6下可以看到生成了两个文件:
libjson_linux-gcc-4.6.1_libmt.a
libjson_linux-gcc-4.6.1_libmt.so
把.a文件拷贝到/usr/local/lib 目录下,为了方便编译给它改个名字libjsonlib.a
4、将jsoncpp目录下的头文件件拷到自己的工程里就可以使用了。
注意在编译里指定动态链接库的地址。 -ljsonlib
例子代码:
#include <iostream>
#include <string>
#include "json/json.h"
int main(void)
{
Json::Value root;
Json::FastWriter fast_writer;
root["REGION_ID"] = "600901";
root["DATA_TOTAL_NUM"] = "456278";
std::cout << fast_writer.write(root) << std::endl;
return 0;
}
输出:{"DATA_TOTAL_NUM":"456278","REGION_ID":"600901"}
例子:
{
"name" : "小楼一夜听春雨",
"age" : 27
}
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
|
#pragma comment(lib, "json_mtd.lib")
#include <fstream>
#include <cassert>
#include "json/json.h"
int
main()
{
ifstream ifs;
ifs.open(
"testjson.json"
);
assert
(ifs.is_open());
Json::Reader reader;
Json::Value root;
if
(!reader.parse(ifs, root,
false
))
{
return
-1;
}
std::string name = root[
"name"
].asString();
int
age = root[
"age"
].asInt();
std::cout<<name<<std::endl;
std::cout<<age<<std::endl;
return
0;
}
|
[{"name" : "xiaoy", "age" :17} , {"name" : "xiaot", "age" : 20}]
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
|
#pragma comment(lib, "json_mtd.lib")
#include <fstream>
#include <cassert>
#include "json/json.h"
int
main()
{
ifstream ifs;
ifs.open(
"testjson.json"
);
assert
(ifs.is_open());
Json::Reader reader;
Json::Value root;
if
(!reader.parse(ifs, root,
false
))
{
return
-1;
}
std::string name;
int
age;
int
size = root.size();
for
(
int
i=0; i<size; ++i)
{
name = root[i][
"name"
].asString();
age = root[i][
"age"
].asInt();
std::cout<<name<<
" "
<<age<<std::endl;
}
return
0;
}
|
json写入:
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
|
#pragma comment(lib, "json_mtd.lib")
#include <fstream>
#include <cassert>
#include "json/json.h"
int
main()
{
Json::Value root;
Json::FastWriter writer;
Json::Value person;
person[
"name"
] =
"hello world"
;
person[
"age"
] = 100;
root.append(person);
std::string json_file = writer.write(root);
ofstream ofs;
ofs.open(
"test1.json"
);
assert
(ofs.is_open());
ofs<<json_file;
return
0;
}
|
结果:[{"age":100,"name":"hello world"}]