在进行配置文件读取或者进行RPC(Remote Produce Call),我们需要在两个进程间传递大量的数据,这时我们一般会选择json/xml/protobuf来序列化数据,加快数据的传输与解析速度。
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。关于json数据格式的具体介绍,大家可以自己去搜索,今天主要介绍下C/C++如何借助第三方库来解析json,进而实现对json的读写。
C/C++本身没有实现字符串到json数据或者json数据到字符串的转换,所以我们需要借助外部的第三方库来实现这个功能,jsoncpp是一个由CPP实现的json数据解析库,通过这个静态库我们可以实现字符串到json,json到字符串,以及读写json文件的功能。
在linux平台上的编译过程如下:
# 安装cmkae
sudo apt-get install cmake
#在源码目录下创建指定目录
cd jsoncpp-1.9.5/
mkdir -p build/debug
cd build/debug
cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
make
生成的libjsoncpp.a需要我们通过编译命令链接到target中,同时指定头文件搜索目录,jsoncpp的头文件保存在jsoncpp-1.9.5/include/json/include下,通常我们只用到json.h
可以通过以下命令链接
g++ -o xxx xxx.cpp -I头文件搜索路径 -L库搜索路径 -l库名称
如果是使用xmake构建项目,则只需要在对应的target下面添加头文件路径,库路径,库名称,如下
add_includedirs("header search path")
add_linkdirs("lib search path")
add_links("static/dynamic library name")
在我们的代码中,需要添加jsoncpp的头文件json.h
在上述工作完成后,就可以在代码中使用jsoncpp来完成对json的各种操作,下面我们来看下该库对json的基本操作
{
"name" : "DeRozan",
"age" : "27",
"sex" : "man"
}
void readStrJson()
{
const char* str =
"{\"name\":\"DeRozan\",\"age\":21,\"sex\":\"man\"}";
Json::Reader reader;
Json::Value root;
//从字符串中读取数据
if (reader.parse(str, root))
{
string name = root["name"].asString();
int age = root["age"].asInt();
string sex = root["sex"].asString();
cout << name + "," << age << "," << sex << endl;
}
}
DeRozan,21,man
{
"name":"Derozan",
"major":[
{
"Player":"LPL player"
},
{
"Player":"Basketball Player"
}]
}
void readStrProJson()
{
string strValue = "{\"name\":\"Derozan\",\"major\":[{\"LPL\":\"EDG player\"},{\"NBA\":\"Basketball Player\"}]}";
Json::Reader reader;
Json::Value value;
if (reader.parse(strValue, value))
{
string out = value["name"].asString();
cout << out << endl;
const Json::Value arrayObj = value["major"];
for (unsigned int i = 0; i < arrayObj.size(); i++)
{
out = arrayObj[i]["Player"].asString();
cout << out<<endl;
}
}
}
DeRozan
LPL player
Basketball Player
{
"age" : 25,
"friends" : {
"friend_age" : 25,
"friend_name" : "Derozan",
"friend_sex" : "man"
},
"hobby" : [ "basket", "women", "sleep" ],
"name" : "Alen",
"sex" : "women"
}
#include
void readFromFile() {
Json::Reader reader;
Json::Value root;
const char* path = "/home/dexu_tian/Tmp/test.json";
std::ifstream infile(path);
if(reader.parse(infile, root)) {
//读取根节点信息
std::string name = root["name"].asString();
int age = root["age"].asInt();
std::string sex = root["sex"].asString();
std::cout << "My name is " << name << std::endl;
std::cout << "I'm " << age << " years old" << std::endl;
std::cout << "I'm a " << sex << std::endl;
//读取子节点信息
std::string friend_name = root["friends"]["friend_name"].asString();
int friend_age = root["friends"]["friend_age"].asInt();
std::string friend_sex = root["friends"]["friend_sex"].asString();
std::cout << "friend's name is " << friend_name << std::endl;
std::cout << "friend's sex is "<<friend_sex << std::endl;
std::cout << "friend is " << friend_age << " years old" << std::endl;
//读取数组信息
std::cout << "my hobby:" << std::endl;
for (unsigned int i = 0; i < root["hobby"].size(); i++)
{
std::string ach = root["hobby"][i].asString();
std::cout << ach << '\t';
}
std::cout << std::endl;
std::cout << "Reading Success!" << std::endl;
}
}
My name is Alen
I'm 25 years old
I'm a women
friend's name is Derozan
friend's sex is man
friend is 25 years old
my hobby:
basket women sleep
Reading Success!
{
"age" : 27,
"friends" : {
"friend_age" : 35,
"friend_name" : "Alen",
"friend_sex" : "man"
},
"hobby" : [ "Basketball", "Swimming", "game" ],
"name" : "Derozan",
"sex" : "man"
}
void writeFileJson()
{
//根节点
Json::Value root;
//根节点属性
root["name"] = Json::Value("Derozan");
root["age"] = Json::Value(27);
root["sex"] = Json::Value("man");
//子节点
Json::Value friends;
//子节点属性
friends["friend_name"] = Json::Value("Alen");
friends["friend_age"] = Json::Value(35);
friends["friend_sex"] = Json::Value("man");
//子节点挂到根节点上
root["friends"] = Json::Value(friends);
//数组形式
root["hobby"].append("Basketball");
root["hobby"].append("Swimming");
root["hobby"].append("game");
//直接输出
//cout << "FastWriter:" << endl;
//Json::FastWriter fw;
//cout << fw.write(root) << endl << endl;
//缩进输出
std::cout << "StyledWriter:" << std::endl;
Json::StyledWriter sw;
std::cout << sw.write(root) << std::endl << std::endl;
//输出到文件
std::ofstream os;
const char* path = "/home/dexu_tian/Tmp/testwrite.json";
os.open(path, std::ios::out | std::ios::app);
if (!os.is_open())
std::cout << "error:can not find or create the file which named \" demo.json\"." << std::endl;
os << sw.write(root);
os.close();
}
//本来代码来源于: https://blog.csdn.net/shuiyixin/article/details/89330529
dexu_tian@VM-4-10-ubuntu:~/Tmp$ cat testwrite.json
{
"age" : 27,
"friends" : {
"friend_age" : 35,
"friend_name" : "Alen",
"friend_sex" : "man"
},
"hobby" : [ "Basketball", "Swimming", "game" ],
"name" : "Derozan",
"sex" : "man"
}
以上就是本文所要分享的内容,希望大家每天坚持进步~
关注wx公众号 “程序员Derozan”, 共同学习。
给个赞支持一下,谢谢啦~