linux下json使用

JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org,本文不再对json做介绍,将重点介绍c++的json解析库的使用方法。json官网上列出了各种语言对应的json解析库,作者仅介绍自己使用过的两种C++的json解析库:jsoncpp(v0.5.0)和Boost(v1.34.0)。

 使用JsonCpp前先来熟悉几个主要的类: 

Json::Value     可以表示里所有的类型,比如int,string,object,array等,具体应用将会在后边示例中介绍。

Json::Reader   将json文件流或字符串解析到Json::Value, 主要函数有Parse。

Json::Writer    与Json::Reader相反,将Json::Value转化成字符串流,注意它的两个子类:Json::FastWriter和Json::StyleWriter,分别输出不带格式的json和带格式的json。

主要包括:从字符串解析,从文件解析,写入文件,读取文件,输出json,读取json等!

环境配置:将解压下的库,头文件和lib添加到指定的位置(可以工程文件夹也可以是环境变量中);


编写 Makefile文件


测试文件和测试代码

测试文件:test.json

{
    "uploadid": "UP000000",
    "code": "0",
    "msg": "",
    "files":
    [
        {
            "code": "0",
            "msg": "",
            "filename": "1D_16-35_1.jpg",
            "filesize": "196690",
            "width": "1024",
            "height": "682",
            "images":
            [
                {
                    "url": "fmn061/20111118",
                    "type": "large",
                    "width": "720",
                    "height": "479"
                },
                {
                    "url": "fmn061/20111118",
                    "type": "main",
                    "width": "200",
                    "height": "133"
                }
            ]
        }
    ]
}

测试代码:

		#include <json/json.h>
		#include <string>
		#include <iostream>
		#include <fstream> 
		#include <string.h>
		using namespace std;

		//返回字符串的长度
		//int getjson(char * buf, string * root)
		int getjson(char * buf, string * root)
		{
		int len = sizeof(*root) ;
		memcpy(buf,root,len);
		//cout << "buf:"<< buf <<endl;
		printf("%s", buf);

		return len;
		}


		int ParseJsonFromFile(const char* filename)
		{
		printf("mingming\n");
		  // 解析json用Json::Reader
		  Json::Reader reader;
		  // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array...
		  Json::Value root;       

		  std::ifstream is;
		  is.open (filename, std::ios::binary );
		  if( !is.is_open() )    
			{   
			cout << "Error opening file\n";   
			return -1;   
			}  

		 cout << is <<endl ;  
		  if (reader.parse(is, root))
				{ 
			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(); 
			cout << code <<endl;
			// 访问节点,Return the member named key if it exist, defaultValue otherwise.
			code = root.get("uploadid", "null").asString();
			cout << code <<endl;
	        // 得到"files"的数组个数
			int file_size = root["files"].size();

			// 遍历数组
			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();
				cout << "type" << ":"<<type <<endl;
				std::string url = val_image[j]["url"].asString();
				cout << "url" << ":"<< url <<endl;
			  }
			}
		  }
		  is.close();
		  return 5;
		}


		//

		int main()
		{   int i;
			char buf[100];
		   
			//从文件读取json流
			ParseJsonFromFile("./test.json");
			
			

			//jie xi zifuchuan
			 string test ="{\"id\":1,\"name\":\"kurama\"}";
			 
			 /*if(reader.parse(test,value))
			 {
					if(!value["id"].isNull())
					{
							 cout << value["id"].asInt() <<endl;
							 cout << value["name"].asString()<<endl;
					 }
			  }*/

		//创建json字符串对象
		Json::Value root;
		root["lUserID"] = Json::Value(1);
		root["name"] = Json::Value("jiaojiao");
		//std::cout << root <<endl;

		Json::StyledWriter my_writer;
		Json::FastWriter my_fwriter;
		//输出json
		std::string ss =  my_fwriter.write(root);


		std::cout << root <<endl;

		std::cout << ss <<endl;
		std::cout << "length:" << ss.length() <<endl;

		Json::Reader reader;
		Json::Value myvalue;
		//直接引用对象的数据
		cout << root["lUserID"].asInt() <<endl;

		//shu chu json
		//解析字符串对象
		if(reader.parse(ss, myvalue))
			 {
		 
					cout << myvalue["lUserID"].asInt() <<endl;
					cout << myvalue["name"].asString()<<endl;
					
			  }

		  /* //直接输出  
			cout << "FastWriter:" << endl;  
			Json::FastWriter fw;  
			cout << fw.write(root) << endl << endl;  
			  
			//缩进输出(格式化输出)  
			cout << "StyledWriter:" << endl;  
			Json::StyledWriter sw;  
			cout << sw.write(root) << endl << endl; */ 

		//输出到文件  
			Json::StyledWriter sw;  
			ofstream os;  
			os.open("./demo.json");  
			os << sw.write(root);  
			os.close(); 
		///////////////////////////
		i = getjson( buf, &ss);

		cout << i <<endl;

		Json::Reader reader0;
		Json::Value myvalue0;

		cout << "haha" << buf <<endl;

		//shu chu json
		//解析字符串对象
		if(reader0.parse(buf, myvalue0))
			 {
		 
					cout << myvalue0["lUserID"].asInt() <<endl;
					cout << myvalue0["name"].asString()<<endl;
					
			  }

		return 0;
		}

出现乱码:

mingming
0x7ffd2f1f9b80
UP000000
UP000000
type:large
url:fmn061/20111118
type:main
url:fmn061/20111118

{
	"lUserID" : 1,
	"name" : "jiaojiao"
}

{"lUserID":1,"name":"jiaojiao"}

length:32
1
1
jiaojiao
****
	{"lUserID":1,"name":"jiaojiao"}

�#****
	�#
32
haha�#

修改程序:用 c_str( )函数将string 对象转换成 char *风格的字符串

#include <json/json.h>
#include <string>
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

//返回字符串的长度
//int getjson(char * buf, string * root)
int getjson(char *buf, string  root)
{
  int len = sizeof(root);
  memcpy(buf, root.c_str(), len);
  //cout << "buf:"<< buf <<endl;
  printf("%s\n", buf);

  return len;
}

int ParseJsonFromFile(const char *filename)
{
  printf("mingming\n");
  // 解析json用Json::Reader
  Json::Reader reader;
  // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array...
  Json::Value root;

  std::ifstream is;
  is.open(filename, std::ios::binary);
  if (!is.is_open())
  {
    cout << "Error opening file\n";
    return -1;
  }

  cout << is << endl;
  if (reader.parse(is, root))
  {
    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();
    cout << code << endl;
    // 访问节点,Return the member named key if it exist, defaultValue otherwise.
    code = root.get("uploadid", "null").asString();
    cout << code << endl;
    // 得到"files"的数组个数
    int file_size = root["files"].size();

    // 遍历数组
    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();
        cout << "type"
             << ":" << type << endl;
        std::string url = val_image[j]["url"].asString();
        cout << "url"
             << ":" << url << endl;
      }
    }
  }
  is.close();
  return 5;
}

//

int main()
{
  int i;
  char buf[100];

  //从文件读取json流
  ParseJsonFromFile("./test.json");

  //jie xi zifuchuan
  string test = "{\"id\":1,\"name\":\"kurama\"}";

  /*if(reader.parse(test,value))
     {
            if(!value["id"].isNull())
            {
                     cout << value["id"].asInt() <<endl;
                     cout << value["name"].asString()<<endl;
             }
      }*/

  //创建json字符串对象
  Json::Value root;
  root["lUserID"] = Json::Value(1);
  root["name"] = Json::Value("jiaojiao");
  //std::cout << root <<endl;

  Json::StyledWriter my_writer;
  Json::FastWriter my_fwriter;
  //输出json
  std::string ss = my_fwriter.write(root);

  std::cout << root << endl;

  std::cout << ss << endl;
  std::cout << "length:" << ss.length() << endl;

  Json::Reader reader;
  Json::Value myvalue;
  //直接引用对象的数据
  cout << root["lUserID"].asInt() << endl;

  //shu chu json
  //解析字符串对象
  if (reader.parse(ss, myvalue))
  {

    cout << myvalue["lUserID"].asInt() << endl;
    cout << myvalue["name"].asString() << endl;
  }

  /* //直接输出  
    cout << "FastWriter:" << endl;  
    Json::FastWriter fw;  
    cout << fw.write(root) << endl << endl;  
      
    //缩进输出(格式化输出)  
    cout << "StyledWriter:" << endl;  
    Json::StyledWriter sw;  
    cout << sw.write(root) << endl << endl; */

  //输出到文件
  Json::StyledWriter sw;
  ofstream os;
  os.open("./demo.json");
  os << sw.write(root);
  os.close();
  ///////////////////////////


  
  cout<<"****\n\t"<<ss<<endl;
 // i = getjson(buf, &ss);
   i = getjson(buf, ss);

  cout<<"****\n\t"<<buf<<endl;

  cout << i << endl;

  Json::Reader reader0;
  Json::Value myvalue0;

  cout << "haha" << buf << endl;

  //shu chu json
  //解析字符串对象
  if (reader0.parse(buf, myvalue0))
  {

    cout << myvalue0["lUserID"].asInt() << endl;
    cout << myvalue0["name"].asString() << endl;
  }

  return 0;
}
mingming
0x7fff019c4890
UP000000
UP000000
type:large
url:fmn061/20111118
type:main
url:fmn061/20111118

{
	"lUserID" : 1,
	"name" : "jiaojiao"
}

{"lUserID":1,"name":"jiaojiao"}

length:32
1
1
jiaojiao
****
	{"lUserID":1,"name":"jiaojiao"}

{"lUserID":1,"name":"jiaojiao"}
6
****
	{"lUserID":1,"name":"jiaojiao"}
6
32
haha{"lUserID":1,"name":"jiaojiao"}
6
1
jiaojiao















猜你喜欢

转载自blog.csdn.net/runner668/article/details/80269054
今日推荐