jsoncpp库使用例子

从json格式的字符串中解析读:

//g++ jsoncpp_read_sample.cpp -I/usr/local/include/jsoncpp -ljsoncpp

#include   
#include   
#include 


int main(void)  
{  
	std::string strjson = "{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\"},{\"key2\":\"value3\"},{\"key2\":\"value4\"}]}";
/*
{	
	"key1":"value1",
	"array":
	[
		{"key2":"value2"},
		{"key2":"value3"},
		{"key2":"value4"}
	]
}
*/  
	Json::Reader reader;  
	Json::Value root;  
	
	if (reader.parse(strjson, root))  
	{  
		std::string out = root["key1"].asString();  
		std::cout << out << std::endl;  
		const Json::Value arrayObj = root["array"];  
		for (int i=0; i


将json对象的值输出:

//g++ jsoncpp_write_sample.cpp -I/usr/local/include/jsoncpp -ljsoncpp

#include   
#include   
#include 


int main(void)  
{
	Json::Value root;  
	Json::Value arrayObj;  
	Json::Value item;  
	
	for (int i = 0; i < 10; i ++)  
	{  
		item["key"] = i;  
		arrayObj.append(item);  
	}  
	
	root["key1"] = "value1";  
	root["key2"] = "value2";  
	root["array"] = arrayObj;  
	//root.toStyledString();  
	//格式化输出Json格式内容
	std::string out = root.toStyledString();  
	std::cout << out << std::endl;  
	std::cout << "--------------------" << std::endl;
	
	//未格式化输出Json格式内容
	Json::FastWriter writer;
	std::string json_str = writer.write(root);
	std::cout << json_str << std::endl;  
	return 0;  
}


从json格式的文件中解析读:

文件内容为

{ 
	"mmac": "e4:95:6e:4e:ed:6e", 
	"wmac": "ff:ff:ff:ff:ff:ff", 
	"data": 
	[ 	{ "mac": "3c:46:d8:19:6a:e3", "rssi": "-82", "tmc": "ff:ff:ff:ff:ff:ff"	}, 
		{ "mac": "90:18:7c:f2:45:cc", "rssi": "-71", "tmc": "ff:ff:ff:ff:ff:ff" }, 
		{ "mac": "b8:44:d9:02:b0:94", "rssi": "-86", "tmc": "ff:ff:ff:ff:ff:ff" }, 
		{ "mac": "dc:85:de:6a:f8:37", "rssi": "-44", "tmc": "ff:ff:ff:ff:ff:ff" }, 
		{ "mac": "ec:0e:c4:60:b7:95", "rssi": "-77", "tmc": "ff:ff:ff:ff:ff:ff" } 
	] 
}


//g++ read_json_file.cpp -I/usr/local/include/jsoncpp -ljsoncpp

#include 
#include   
#include   
#include 
#include 

int main(void)  
{  
	std::ifstream ifs;
	
	ifs.open("test.json");
	
	assert(ifs.is_open());
	
	Json::Reader reader;
	Json::Value root;
	
	if (!reader.parse(ifs, root, false))
	{
		std::cout<<"reader.parse() fail"<mac  " << out << std::endl;  
			
		out = arrayObj[i]["rssi"].asString();  
		std::cout << "data-->rssi  " << out << std::endl; 

		out = arrayObj[i]["tmc"].asString();  
		std::cout << "data-->tmc  " << out << std::endl; 
		
	}
	
	return 0; 
} 




你可能感兴趣的:(linux,C)