c++ json 詳解


 一. 使用jsoncpp解析json

Jsoncpp是個跨平台的開源庫,首先從http://jsoncpp.sourceforge.net/上下載jsoncpp庫源碼,我下載的是v0.5.0,壓縮包大約107K,解壓,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到jsoncpp.sln,用VS2003及以上版本編譯,默認生成靜態鏈接庫。 在工程中引用,只需要include/json及.lib文件即可。

 使用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。

 1. 從字符串解析json

  1. int ParseJsonFromString()  
  2. {  
  3.   const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
  4.   
  5.   Json::Reader reader;  
  6.   Json::Value root;  
  7.   if (reader.parse(str, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素   
  8.   {  
  9.     std::string upload_id = root["uploadid"].asString();  // 訪問節點,upload_id = "UP000000"   
  10.     int code = root["code"].asInt();    // 訪問節點,code = 100   
  11.   }  
  12.   return 0;  
  13. }  
int ParseJsonFromString()
{
  const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";

  Json::Reader reader;
  Json::Value root;
  if (reader.parse(str, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素
  {
    std::string upload_id = root["uploadid"].asString();  // 訪問節點,upload_id = "UP000000"
    int code = root["code"].asInt();    // 訪問節點,code = 100
  }
  return 0;
}

2. 從文件解析json

json文件內容:

  1. {  
  2.     "uploadid": "UP000000",  
  3.     "code": "0",  
  4.     "msg": "",  
  5.     "files":  
  6.     [  
  7.         {  
  8.             "code": "0",  
  9.             "msg": "",  
  10.             "filename": "1D_16-35_1.jpg",  
  11.             "filesize": "196690",  
  12.             "width": "1024",  
  13.             "height": "682",  
  14.             "images":  
  15.             [  
  16.                 {  
  17.                     "url": "fmn061/20111118",  
  18.                     "type": "large",  
  19.                     "width": "720",  
  20.                     "height": "479"  
  21.                 },  
  22.                 {  
  23.                     "url": "fmn061/20111118",  
  24.                     "type": "main",  
  25.                     "width": "200",  
  26.                     "height": "133"  
  27.                 }  
  28.             ]  
  29.         }  
  30.     ]  
  31. }  
{
    "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"
                }
            ]
        }
    ]
}

 解析代碼:

  1. int ParseJsonFromFile(const char* filename)  
  2. {  
  3.   // 解析json用Json::Reader   
  4.   Json::Reader reader;  
  5.   // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array...   
  6.   Json::Value root;         
  7.   
  8.   std::ifstream is;  
  9.   is.open (filename, std::ios::binary );    
  10.   if (reader.parse(is, root))  
  11.   {  
  12.     std::string code;  
  13.     if (!root["files"].isNull())  // 訪問節點,Access an object value by name, create a null member if it does not exist.   
  14.       code = root["uploadid"].asString();  
  15.       
  16.     // 訪問節點,Return the member named key if it exist, defaultValue otherwise.   
  17.     code = root.get("uploadid", "null").asString();  
  18.   
  19.     // 得到"files"的數組個數   
  20.     int file_size = root["files"].size();  
  21.   
  22.     // 遍歷數組   
  23.     for(int i = 0; i < file_size; ++i)  
  24.     {  
  25.       Json::Value val_image = root["files"][i]["images"];  
  26.       int image_size = val_image.size();  
  27.       for(int j = 0; j < image_size; ++j)  
  28.       {  
  29.         std::string type = val_image[j]["type"].asString();  
  30.         std::string url = val_image[j]["url"].asString();  
  31.       }  
  32.     }  
  33.   }  
  34.   is.close();  
  35.   return 0;  
  36. }  
int ParseJsonFromFile(const char* filename)
{
  // 解析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 (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();
    
    // 訪問節點,Return the member named key if it exist, defaultValue otherwise.
    code = root.get("uploadid", "null").asString();

    // 得到"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();
        std::string url = val_image[j]["url"].asString();
      }
    }
  }
  is.close();
  return 0;
}

 3. 在json結構中插入json

  1. Json::Value arrayObj;   // 構建對象   
  2. Json::Value new_item, new_item1;  
  3. new_item["date"] = "2011-12-28";  
  4. new_item1["time"] = "22:30:36";  
  5. arrayObj.append(new_item);  // 插入數組成員   
  6. arrayObj.append(new_item1); // 插入數組成員   
  7. int file_size = root["files"].size();  
  8. for(int i = 0; i < file_size; ++i)  
  9.   root["files"][i]["exifs"] = arrayObj;   // 插入原json中  
    Json::Value arrayObj;   // 構建對象
    Json::Value new_item, new_item1;
    new_item["date"] = "2011-12-28";
    new_item1["time"] = "22:30:36";
    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中

 4. 輸出json

  1. // 轉換為字符串(帶格式)   
  2. std::string out = root.toStyledString();  
  3. // 輸出無格式json字符串   
  4. Json::FastWriter writer;  
  5. std::string out2 = writer.write(root);  
// 轉換為字符串(帶格式)
std::string out = root.toStyledString();
// 輸出無格式json字符串
Json::FastWriter writer;
std::string out2 = writer.write(root);

jsoncpp的一些使用方法介紹:

1、初始化

Json::Value root;

Json::Reader reader;

reader.parse(“{“name”:”sunny”}”, root);

Reader可以用來初始化一個人json從字符串。

2、讀取json文件初始化

這是我寫的一個方法:

 
[cpp]  view plain copy
 
  1. Json::Value BYJsonDataManager::getJsonFromFile(const char* fileName){  
  2.     Json::Reader reader;  
  3.     ifstream file(getFullPath(fileName));  
  4.     CCAssert(file.is_open(), "file is open fail!");  
  5.     Json::Value root;  
  6.     if  (!reader.parse(file, root, false )) {  
  7.         CCAssert(false, "Json::Reader Parse error!");  
  8.     }  
  9.     return root;  
  10. }  

3、解析json

首先生成一個json

Json::Value myjson = getJsonFromFile(“test.json”);  //利用上面的函數生成一個json。

int num = myJson["num"].asInt();

string str = myJson["name"].asString();

 

4、json數組

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。

int i = 0;

Json::Value arr = myjson[i]; //獲取arr數組的第一個元素

 

5、利用迭代器獲取json的key。(有時候並不知道json的key,這個時候可以利用迭代器獲取json的key)

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。

Json::Value::Members members(myjson.getMemberNames());

for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it)  {
const std::string &key = *it;
}

6、自己拼裝Json數組,(有時候發往服務器的數據是一個json數據)

Json::Value arr;

for(int i = 0 ;i < 5;++i){

Json::Value myjson = getJsonFromFile(“test.json”);//利用上面的函數生成一個json。

arr.append(protocolData);

}

如果想讓這個jsonArr有key。

Json::Value arr2;

arr2["array"] = arr;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM