C/C++读写JSON数据的详细过程记录

前言

在进行配置文件读取或者进行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文件的功能。

1.下载 jsoncpp github源码下载地址,目前已经release了63个版本,可以选择一个比较新的版本下载source code.

2.编译安装

在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在 jsoncpp-1.9.5/build/debug/lib目录下。 执行上述命令即可完成编译,详细说明可以点击 此处查看

3.链接

生成的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基础用法

在上述工作完成后,就可以在代码中使用jsoncpp来完成对json的各种操作,下面我们来看下该库对json的基本操作

1.从字符串中读取json

1.1 简单json数据 (单层数据)定义一个字符串来存储json数据

{
    "name" : "DeRozan",
    "age" : "27",
    "sex" : "man"
}

使用json数据库读取字符串到json对象

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

1.2 嵌套json数据

json中包含多层嵌套数据

{
    "name":"Derozan",
    "major":[
    {
        "Player":"LPL player"
    },
    {
        "Player":"Basketball Player"
    }]
}

使用jsoncpp读取多级json数据

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

2.从文件中读取json

test.json

{
   "age" : 25,
   "friends" : {
      "friend_age" : 25,
      "friend_name" : "Derozan",
      "friend_sex" : "man"
   },
   "hobby" : [ "basket", "women", "sleep" ],
   "name" : "Alen",
   "sex" : "women"
}
#include <fstream>

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!

3.写入json文件

准备写入的json内容

{
   "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"
}

总结

到此这篇关于C/C++读写JSON数据的文章就介绍到这了,更多相关C/C++读写JSON数据内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年5月13日 上午7:45
下一篇 2023年5月13日 上午7:47

相关推荐