Jsoncpp编译与使用基础

                                   Jsoncpp编译与使用基础

                                                                          ---唠叨一句:不积跬步无以至千里

1、Json编译

1.1   库准备

Jsoncpp库(jsoncpp-src-0.5.0.tar.gz)下载地址:

http://sourceforge.net/projects/jsoncpp/

Jsoncpp的编译辅助工具cons(Linux下必须):

http://sourceforge.net/projects/scons/files/scons/2.1.0/scons-2.1.0.tar.gz/download

1.2  Windows编译(vs2015)

   Windows下编译比较简单,解压jsoncpp-src-0.5.0.tar.gz,

    进入解压后文件jsoncpp-src-0.5.0\makefiles\vs71,用vs2015打开jsoncpp.sln,点击确定升级到vs2015(vc14)编译器。

         

     顺利进入项目进行简单的设置,设置为Release x64,如下图

         

    接着右击lib_json,选择生成,片刻编译完成。在x64->Release下就有静态库json_vc71_libmt.lib,接下来整理出来include及lib。

1.3  Linux编译(参考下面链接,很详细)

https://www.cnblogs.com/SZxiaochun/p/7684454.html

大致步骤:

(1)解压tar -zvxf scons-2.1.0.tar.gz

(2)cd到解压目录下,终端输入命令  sudo python setup.py install

(3)接着解压jsoncpp-src-0.5.0.tar.gz :tar -zvxf jsoncpp-src-0.5.0.tar.gz

(4)cd到解压目录下,输入命令 sudo scons platform=linux-gcc

     这个时候在jsoncpp-src-0.5.0/libs/linux-gcc-4.9.1/下生成了编译好的静态库和动态库(libjson_linux-gcc-4.9.1_libmt.a和libjson_linux-gcc-4.9.1_libmt.so)。

(5)使用的时候可以选择配置到系统中或者在使用时写进CMakeLists.txt。

2、Json基础使用

在windows下vs2015配置比较简单,就像配置普通静态库一样,包含目录、库目录和链接库。

2.1   从文件解析json

#include<iostream>
#include<string>
#include<vector>
#include<json/json.h>
#include<ostream>
#include <fstream>
int ReadJsonFromFile(const char* filename)
{
	Json::Reader reader;// 解析json用Json::Reader   
	Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array         

	std::ifstream is;
	is.open(filename, std::ios::binary);
	if (reader.parse(is, root,false))
	{
		std::string code;
		if (!root["files"].isNull())  // 访问节点,Access an object value by name, create a null member if it does not exist.  
			code = root["uploadid"].asString();

		code = root.get("uploadid", "null").asString();// 访问节点,Return the member named key if it exist, defaultValue otherwise.    

		int file_size = root["files"].size();  // 得到"files"的数组个数  
		for (int i = 0; i < file_size; ++i)  // 遍历数组  
		{
			Json::Value val_image = root["files"][i]["images"];
			int image_size = val_image.size();
			for (int j = 0; j < image_size; ++j)
			{
				std::string type = val_image[j]["type"].asString();
				std::string url = val_image[j]["url"].asString();
				printf("type : %s, url : %s \n", type.c_str(), url.c_str());
			}
		}
	}
	is.close();

	return 0;
}

2.2 从string字符串解析json

void ReadJsonFromString(const std::string strData)
{
	Json::Reader reader;
	Json::Value root;
	if (reader.parse(strData, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素  
	{
		std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"  
		int code = root["code"].asInt();                              //  访问节点,code = 100 
	}
}

2.3 从char*解析json

void ReadJsonFromChars(const char* strData) {
	Json::Reader reader;
	Json::Value root;
	if (reader.parse( strData, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素  
	{
		std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"  
		int code = root["code"].asInt();                              //  访问节点,code = 100 
	}
}

2.4 json序列化,即写入json对象到string或者char*字符串,注意:具体数值根据实际应用确定,所有没有参数

void CreateJson() {
	Json::FastWriter writerinfo;
	Json::Value resultinfo;

	resultinfo["status"] = 0;
	resultinfo["message"] = "successed";
	resultinfo["num_"] = 1;
	resultinfo["t_flag"] = 1;
	resultinfo["exception_flag"] = 1001;
	resultinfo["image_path"] = "/home/images/kitti.jpg";

	//json 数组
	for (int i = 0; i < 2; i++) {
		Json::Value body_node;
		body_node["x"] = 871;
		body_node["y"] = 531;
		body_node["width"] = 68;
		body_node["height"] = 52;
		body_node["num_1"] = 0;
		body_node["num_2"] = 1;
		resultinfo["info"].append(body_node);
	}
	std::string json_string = writerinfo.write(resultinfo);
	std::cout << json_string << std::endl;
}

2.5 json序列化并写入到json文件中

Json::FastWriter writerinfo;
	Json::Value resultinfo;

	resultinfo["status"] = 0;
	resultinfo["message"] = "successed";
	resultinfo["num_body"] = 1;
	resultinfo["alert_flag"] = 1;
	resultinfo["clothes_exception_flag"] = 1001;
	resultinfo["image_path"] = "/home/images/kitti.jpg";

	//json 数组
	for (int i = 0; i < 2; i++) {
		Json::Value body_node;
		body_node["x"] = 871;
		body_node["y"] = 531;
		body_node["width"] = 68;
		body_node["height"] = 52;
		body_node["num_blouse"] = 0;
		body_node["num_trousers"] = 1;
		resultinfo["body_info"].append(body_node);
	}
	std::string json_string = writerinfo.write(resultinfo);
	std::cout << json_string << std::endl;

	//将json对象存入json文件中
	std::ofstream ofs;
	ofs.open("test_write.json");
	ofs << json_string;
	ofs.close();
}

2.6 向原来json文件中插入新的json

 

void InsertJsonData2File(const char* filename)
{
	Json::Reader reader;
	Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array        

	std::ifstream is;
	is.open(filename, std::ios::binary);
	if (reader.parse(is, root))
	{
		Json::Value arrayObj;   // 构建对象  
		Json::Value new_item, new_item1;
		new_item["date"] = "2011-11-11";
		new_item1["time"] = "11:11:11";
		arrayObj.append(new_item);  // 插入数组成员  
		arrayObj.append(new_item1); // 插入数组成员  
		int file_size = root["files"].size();
		for (int i = 0; i < file_size; ++i)
			root["files"][i]["exifs"] = arrayObj;   // 插入原json中 
		std::string out = root.toStyledString();
		// 输出无格式json字符串  
		Json::FastWriter writer;
		std::string strWrite = writer.write(root);
		std::ofstream ofs;
		ofs.open("test_write.json");
		ofs << strWrite;
		ofs.close();
	}

	is.close();
}

 

猜你喜欢

转载自blog.csdn.net/ouyangfushu/article/details/84993791