jsoncpp的api簡要說明


1  jsoncpp的api簡要說明

1,解析(json字符串轉為對象)

std::string strDataJson;

Json::Reader JReader; 

Json::Value JObject;

if (!JReader.parse(strDataJson, JObject))

{

cerr << "parse json error." << endl;

return bSuccess;

}

 

2,讀取

std::string strMsg = JRec["msg"].asString();

int nRetCode = JRec["ret"]..asInt();

Json::Value JList = JRec["data"]["list"];

int nSize = JList.size();

 

獲取錯誤信息: JReader.getFormatedErrorMessages()

 

3,增加或修改

JRoot["stringdata"] = Json::Value("msg");

JRoot["intdata"] = Json::Value(10);

 

4,刪除

JValue.removeMember("toberemove");

 

5,對象轉為字符串

//輸出無格式json字符串

Json::FastWriter fast_writer;

strJRecList = fast_writer.write(JRoot);

 

//格式化之后的json,有回車換行符

std::string strOut = JRoot.toStyledString();

#include "json/json.h"
const string fileName = "json.txt";

int main(int argc, char *argv[])
{
    string line;
    std::ifstream in(fileName.c_str());
    if(!in)
        return 0;

    std::getline(in, line);

    Json::Reader reader;  
    Json::Value root;  

    if(reader.parse(line, root))
        cout << "suc" << endl;
    else
        cout << "fail" << endl;

   cout << root["status"].asInt() << endl;
   cout << root["msg"].asString() << endl;
   cout << root["forbidReason"].asString() << endl;

 

    Json::Value root, ipPort;
    string host;
    unsigned int port = 0;

    if(addrs.size() == 0)
        root["hosts"].append(ipPort);
    else
    {   
        for(size_t i = 0; i < addrs.size(); i++)
        {   
            if(getIpAndPort(addrs[i], host, port))
            {   
                ipPort["ip"] = host;
                ipPort["port"] = port;
            }   
            root["hosts"].append(ipPort);
        }   
    }

 

http://blog.csdn.net/u014489596/article/details/44920557

 

son是一種數據交換格式,比較適合編寫和閱讀。jsoncpp是采用c++語言編寫的用來處理json格式的第三包。直接來說明改如何使用它,本文是基於windows下的。

 

在github上下載jsoncpp的源代碼包:https://github.com/open-source-parsers/jsoncpp。解壓后用vs打開/makefiles/vs71/jsoncpp.sln項目,選擇lib_json項目編譯來生成lib文件,為了方便,debug和release都需要生成。

 

創建一個win32的空項目,將生成的lib文件包含,附加包含目錄添加源代碼中的include文件夾。后面簡單說下比較常用的幾種json處理方法。

 

解析json對象:

 

1.首先看看最簡單的一種json格式,只有鍵-值的一重嵌套:

{

“id” : 123,

"name" : "wu"

}

我們直接將上面的數據初始化到到string對象中,方便解析,后面都是如此

 

[cpp]  view plain copy
 
  1. std::string json = "{\"id\" : 123, \"name\" : \"wu\"}";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. if (reader.parse(json, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素     
  8. {    
  9.     name = root["name"].asString();  
  10.     id = root["id"].asInt();  
  11. }  


        2.再看看數組的:

 

[ { "id" : 1, "name" : "wu"},  {"id":2, "name" : "tan"} ]

 

[cpp]  view plain copy
 
  1. std::string json = "[ {\"id\" : 1, \"name\" : \"wu\"}, {\"id\" : 2, \"name\" : \"tan\"} ]";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. std::map<int, std::string> mapJson;  
  8.   
  9. if (reader.parse(json, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素     
  10. {    
  11.     for (int i = 0; i < root.size(); ++i)  
  12.     {  
  13.         name = root[i]["name"].asString();  
  14.         id = root[i]["id"].asInt();  
  15.   
  16.         mapJson[id] = name;  
  17.     }  
  18. }   


        3.如果是這樣的數組:

 

{

“id” : [1, 2],

"name" : ["wu", "tan"]

}

[cpp]  view plain copy
 
  1. std::string json = "{\"id\" : [1, 2], \"name\" : [\"wu\", \"tan\"] } ";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7.   
  8. if (reader.parse(json, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素     
  9. {    
  10.     for (int i = 0; i < root["id"].size(); ++i)  
  11.     {  
  12.         id = root["id"][i].asInt();  
  13.     }  
  14.   
  15.     for (int i = 0; i < root["name"].size(); ++i)  
  16.     {  
  17.         name = root["name"][i].asString();  
  18.     }  
  19. }   

 

這種情況其實和上一種是類似的。

 

4.看看多重嵌套的情況,為了簡便,我們嵌套兩層:

{

"id" : 1,

"data" : {

"name" : "wu",

“age” : 26

}

}

[cpp]  view plain copy
 
  1. std::string json = "{\"id\" : 1, \"data\" : { \"name\" : \"wu\",  \"age\" : 26 } }";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. int age = 0;  
  8.   
  9. if (reader.parse(json, root))  // reader將Json字符串解析到root,root將包含Json里所有子元素     
  10. {    
  11.     id = root["id"].asInt();  
  12.     name = root["data"]["name"].asString();  
  13.     age = root["data"]["age"].asInt();  
  14. }   

 

其實這種情況和第一種的類似,只是通過root["key"]取到的還是鍵值對,繼續通過key取值即可。

基本上再復雜的數據格式也是上面幾種情況的組合而已。

 

json對象的生成:

1.生成上面第一種情況的json格式:

 

[cpp]  view plain copy
 
  1. Json::Value root;    
  2.   
  3. root["id"] = 123;  
  4. root["name"] = "wu";  
  5.       
  6. std::string json = root.toStyledString();  


我們會將生成的json對象序列化到string對象中去,后面也是如此。

 

 

2.生成上面第二種情況的json:

 

[cpp]  view plain copy
 
  1. Json::Value root;  
  2.   
  3. for (int i = 0; i < 2; ++i)  
  4. {  
  5.     root[i]["id"] = i + 1;  
  6.   
  7.     if (0 == i)  
  8.     {  
  9.         root[i]["name"] = "wu";  
  10.     }  
  11.     else  
  12.     {  
  13.         root[i]["name"] = "tan";  
  14.     }  
  15. }  
  16.   
  17. std::string json = root.toStyledString();  


還可以這樣生成:

 

 

[cpp]  view plain copy
 
  1. Json::Value root;  
  2. Json::Value item;  
  3.   
  4. for (int i = 0; i < 2; ++i)  
  5. {  
  6.     item["id"] = i + 1;  
  7.   
  8.     if (0 == i)  
  9.     {  
  10.         item["name"] = "wu";  
  11.     }  
  12.     else  
  13.     {  
  14.         item["name"] = "tan";  
  15.     }  
  16.           
  17.     root.append(item);  
  18. }  
  19.   
  20. std::string json = root.toStyledString();  


3.生成上面第三種情況的json:

 

 

[cpp]  view plain copy
 
  1. Json::Value root;  
  2.   
  3. for (int i = 0; i < 2; ++i)  
  4. {  
  5.     root["id"].append(i);  
  6.   
  7.     if (0 == i)  
  8.     {  
  9.         root["name"].append("wu");  
  10.     }  
  11.     else  
  12.     {  
  13.         root["name"].append("tan");  
  14.     }  
  15.   
  16. }  
  17.   
  18. std::string json = root.toStyledString();  


4.生成上面第四種情況的json:

 

 

[cpp]  view plain copy
 
  1. Json::Value root;  
  2.   
  3. root["id"] = 1;  
  4. root["data"]["name"] = "wu";  
  5. root["data"]["age"] = 26;  
  6.   
  7. std::string json = root.toStyledString();  



其實解析和生成json是互逆的,只要明白這幾種情況,其他的無非是這幾種情況的各種組合,原理是一樣的。

 

版權聲明:本文為博主原創文章,未經博主允許不得轉載。

 


免責聲明!

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



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