Json和Xml相比有個最大的優勢,基於字串。xml必須與檔案相關,而json只是字串(當然也提供了與檔案相關的操作)。 Let's say it from my code: [cpp] #include <json/json.h> //解壓後找到目錄 vs71,用vs開啟然後產生解決方案,本程式直接在jsontest.cpp中改寫的 #include <iostream> #include <fstream> #include <string> using namespace std; const string g_file = "json.c"; //原本以為vs開啟該檔案後會對json格式字串做一個format,結果和記事本開啟一樣,不如xml條理清晰 // 此處兩個結構體並沒有用到,他們的目的只是讓我們看清楚json字串的格式 struct Address { string name; //街道名 int number; //街道號 }; struct Student { int no; //學好 string name; //名字 Address addr; //家庭地址 }; void Write() { Json::Value root; //根(如果樹的根一樣) int no[] = { 2008, 2010, 2013 }; string name[] = { "sumos", "fly away", "sun"}; string name2[] = { "西湖路", "東湖路", "中南海" }; int number[] = { 101, 202, 303 }; for(int k = 0; k < 3; k++) { Json::Value person, addr; person["no"] = Json::Value(no[k]); person["name"] = Json::Value(name[k]); addr["name"] = Json::Value(name2[k]); addr["number"] = Json::Value(number[k]); person["address"] = addr; root.append(person); } Json::FastWriter writer; // FastWriter沒有Encode ofstream out; out.open(g_file); if(out.is_open()) { out<< writer.write(root); out.close(); } } void Read() { ifstream in; in.open(g_file); if( ! in.is_open() ) return; Json::Reader reader; Json::Value root; bool r = reader.parse(in,root); if( ! r ) { in.close(); return; } int n = root.size(); for(int k = 0; k < n; k++) { Json::Value person = root[k]; cout<< person["no"].asInt() << person["name"].asString() <<endl; Json::Value addr = person["address"]; cout<< addr["name"].asString() << addr["number"].asInt() <<endl <<endl; } in.close(); } int main(int,char**) { Read(); system("pause"); return 0; } 好吧,感覺不需要什麼注釋就可以很輕鬆的明白了