Json學習劄記

來源:互聯網
上載者:User

    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;  }  好吧,感覺不需要什麼注釋就可以很輕鬆的明白了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.