【jsoncpp】c++解析json数据包

对着背影说爱祢 提交于 2019-11-28 01:16:26
  • 安装jsoncpp apt-get install libjsoncpp-dev
  • 项目中加入头文件#include <jsoncpp/json/json.h>
  • 编译命令后面加上-ljsoncpp
  • 用下面的代码和makefile进行测试,是否安装成功。
//test.cpp
#include <iostream>   
#include <string>   
#include <jsoncpp/json/json.h>
using namespace std;  
int main(){  
	Json::Value json_temp;
	json_temp["name"] = Json::Value("sharexu");
	json_temp["age"] = Json::Value(18);
	Json::Value root; 
	root["key_string"] = Json::Value("value_string");
	root["key_number"] = Json::Value(12345); 
	root["key_boolean"] = Json::Value(false);
	root["key_double"] = Json::Value(12.345); 
	root["key_object"] = json_temp; 
	root["key_array"].append("array_string");
	root["key_array"].append(1234); 
	
	Json::FastWriter fast_writer;
	std::cout << fast_writer.write(root);
	
	Json::StyledWriter styled_writer;
	std::cout << styled_writer.write(root);
	
	string str_test ="{\"id\":1,\"name\":\"pacozhong\"}";
	Json::Reader reader;
	Json::Value value;
	if (!reader.parse(str_test, value))
		return 0;
	string value_name=value["name"].asString(); 
	cout <<value_name<<endl;
	cout <<value["name"];
	if(!value["id"].isInt()){
		cout<<"id is not int"<<endl;
	}else{
		int value_id=value["id"].asInt(); 
		cout<<value_id<<endl;
	}	
	return 0;
}

  • makefile
test:test.o
	g++ -o test test.o -ljsoncpp
test.o:test.cpp
	g++ -c test.cpp -ljsoncpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!