標籤:style blog http color os ar 使用 java for
最近開始使用 jsoncpp,以前一直在使用cJSON,但是使用cJSON的時候經常會忘記free掉json的記憶體,結果造成了記憶體泄露,程式跑著跑著就崩潰了。所以最近把json轉移到了jsoncpp上。
jsoncpp的代碼源檔案放在了百度網盤 : http://pan.baidu.com/s/1ntqQhIT 或 jsoncpp.zip
下面是jsoncpp原始碼中的test執行個體,大家感受一下啊。
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 : [email protected]
jsoncpp代碼執行個體