C++ 解析Json——jsoncpp

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录。
Jsoncpp是个跨平台的开源库,下载地址: http://sourceforge.net/projects/jsoncpp/ ,我下载的是v0.5.0,压缩包大约104K。

方法一:使用Jsoncpp生成的lib文件
       解压上面下载的 Jsoncpp 文件,在jsoncpp-src-0.5.0/makefiles/vs71目录里找到jsoncpp.sln,用VS2008版本编译,默认生成静态链接库。 在工程中引用,只需要包含include/json下的头文件及生成的.lib文件即可。
       如何包含lib文件:在.cpp文件中 #pragma comment(lib."json_vc71_libmt.lib"),在工程属性中Linker下Input中Additional Dependencies写入lib文件名字(Release下为 json_vc71_libmt.lib,Debug为 json_vc71_libmtd.lib

注意: Jsoncpp的lib工程编译选项要和VS工程中的编译选项保持一致。如lib文件工程编译选项为MT(或MTd),VS工程中也要选择MT (或MTd),否则会出现编译错误问题,debug和release下生成的lib文件名字不同,注意不要看错了,当成一个文件来使用(我就犯了这个错误)。

方法二:使用Jsoncpp包中的.cpp .h文件
       解压上面下载的 Jsoncpp 文件,把 jsoncpp-src-0.5.0文件拷贝到工程目录下, jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\src\lib_json 目录里的文件包含到VS工程中,在VS工程的属性C/C++下General中 Additional Include Directories 包含头文件目录 .\jsoncpp-src-0.5.0\include 。在使用的cpp文件中 包含json头文件即可,如: #include "json/json.h" 。将 json_reader.cpp、 json_value.cpp和 json_writer.cpp三个文件的Precompiled Header属性设置为 Not Using Precompiled Headers 否则编译会出现错误。

jsoncpp 使用详解

jsoncpp 主要包含三种类型的 class:Value、Reader、Writer。jsoncpp 中所有对象、类名都在 namespace Json 中,包含 json.h 即可。

Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。


下面是从网上找的代码示例:

1. 从字符串解析json

[cpp]  view plain  copy
  1. const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";    
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素    
  6. {    
  7.     std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"    
  8.     int code = root["code"].asInt();    // 访问节点,code = 100   
  9. }    

2. 从文件解析json

[cpp]  view plain  copy
  1. int ReadJsonFromFile(const char* filename)    
  2. {    
  3.     Json::Reader reader;// 解析json用Json::Reader     
  4.     Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array           
  5.   
  6.     std::ifstream is;    
  7.     is.open (filename, std::ios::binary );      
  8.     if (reader.parse(is, root, FALSE))    
  9.     {    
  10.         std::string code;    
  11.         if (!root["files"].isNull())  // 访问节点,Access an object value by name, create a null member if it does not exist.    
  12.             code = root["uploadid"].asString();    
  13.           
  14.         code = root.get("uploadid""null").asString();// 访问节点,Return the member named key if it exist, defaultValue otherwise.      
  15.   
  16.         int file_size = root["files"].size();  // 得到"files"的数组个数    
  17.         for(int i = 0; i < file_size; ++i)  // 遍历数组    
  18.         {    
  19.             Json::Value val_image = root["files"][i]["images"];    
  20.             int image_size = val_image.size();    
  21.             for(int j = 0; j < image_size; ++j)    
  22.             {    
  23.                 std::string type = val_image[j]["type"].asString();    
  24.                 std::string url  = val_image[j]["url"].asString();   
  25.                 printf("type : %s, url : %s \n", type.c_str(), url.c_str());  
  26.             }    
  27.         }    
  28.     }    
  29.     is.close();    
  30.   
  31.     return 0;    
  32. }  


3. 向文件中插入json

[cpp]  view plain  copy
  1. void WriteJsonData(const char* filename)  
  2. {  
  3.     Json::Reader reader;    
  4.     Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array          
  5.   
  6.     std::ifstream is;    
  7.     is.open (filename, std::ios::binary );      
  8.     if (reader.parse(is, root))    
  9.     {    
  10.         Json::Value arrayObj;   // 构建对象    
  11.         Json::Value new_item, new_item1;    
  12.         new_item["date"] = "2011-11-11";    
  13.         new_item1["time"] = "11:11:11";    
  14.         arrayObj.append(new_item);  // 插入数组成员    
  15.         arrayObj.append(new_item1); // 插入数组成员    
  16.         int file_size = root["files"].size();    
  17.         for(int i = 0; i < file_size; ++i)    
  18.             root["files"][i]["exifs"] = arrayObj;   // 插入原json中   
  19.         std::string out = root.toStyledString();    
  20.         // 输出无格式json字符串    
  21.         Json::FastWriter writer;    
  22.         std::string strWrite = writer.write(root);  
  23.         std::ofstream ofs;  
  24.         ofs.open("test_write.json");  
  25.         ofs << strWrite;  
  26.         ofs.close();  
  27.     }    
  28.   
  29.     is.close();    
  30. }  

数组循环解析,使用方法如下:

[cpp]  view plain  copy
  1. if(!root["list"].isNull())  
  2. {  
  3.   for (int nIndex = 0; nIndex < root["list"].size(); nIndex++)  
  4.   {  
  5.     CString sTitleTemp = root["list"][nIndex]["title"].asCString();  
  6.   }  
  7. }  

猜你喜欢

转载自blog.csdn.net/u013472838/article/details/80006553