jsoncpp代碼實例


最近開始使用 jsoncpp,以前一直在使用cJSON,但是使用cJSON的時候經常會忘記free掉json的內存,結果造成了內存泄露,程序跑着跑着就崩潰了。所以最近把json轉移到了jsoncpp上。

jsoncpp的代碼源文件 百度網盤 : http://pan.baidu.com/s/1ntqQhIT

下面是jsoncpp源代碼中的main.cpp實例,大家感受一下。

jsoncpp代碼包解壓后的目錄結構如下:

jsoncpp/
├─ include
│   └─ json
│       ├── autolink.h
│       ├── config.h
│       ├── features.h
│       ├── forwards.h
│       ├── json.h
│       ├── reader.h
│       ├── value.h
│       └── writer.h
├─ makefile
└─ src
    ├─ json
    │   ├── json_batchallocator.h
    │   ├── json_internalarray.inl
    │   ├── json_internalmap.inl
    │   ├── json_reader.cpp
    │   ├── json_value.cpp
    │   ├── json_valueiterator.inl
    │   ├── json_writer.cpp
    │   └── sconscript
    └── main.cpp

其中jsoncpp/src/main.cpp就是我們的測試程序代碼。

在jsoncpp目錄下直接運行命令make即可進行編譯(linux環境下)。

 1 #include <string>
 2 #include <json/json.h>
 3 
 4 void readJson();
 5 void writeJson();
 6 
 7 int main(int argc, char** argv) {
 8     readJson();
 9     writeJson();
10     return 0;
11 }
12 
13 void readJson() {
14     using namespace std;
15     std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
16 
17     Json::Reader reader;
18     Json::Value value;
19 
20     if (reader.parse(strValue, value))
21     {
22         std::string out = value["name"].asString();
23         std::cout << out << std::endl;
24         const Json::Value arrayObj = value["array"];
25         for (unsigned int i = 0; i < arrayObj.size(); i++)
26         {
27             if (!arrayObj[i].isMember("cpp")) 
28                 continue;
29             out = arrayObj[i]["cpp"].asString();
30             std::cout << out;
31             if (i != (arrayObj.size() - 1))
32                 std::cout << std::endl;
33         }
34     }
35 }
36 
37 void writeJson() {
38     using namespace std;
39 
40     Json::Value root;
41     Json::Value arrayObj;
42     Json::Value item;
43 
44     item["cpp"] = "jsoncpp";
45     item["java"] = "jsoninjava";
46     item["php"] = "support";
47     arrayObj.append(item);
48 
49     root["name"] = "json";
50     root["array"] = arrayObj;
51 
52     root.toStyledString();
53     std::string out = root.toStyledString();
54     std::cout << out << std::endl;
55 }

 

下面是運行的結果

 1 json
 2 jsoncpp
 3 {
 4    "array" : [
 5       {
 6          "cpp" : "jsoncpp",
 7          "java" : "jsoninjava",
 8          "php" : "support"
 9       }
10    ],
11    "name" : "json"
12 }

 

作者:風波

mail : fengbohello@qq.com

 


免責聲明!

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



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