• Mongodb C++ 的简易封装


    Mongodb.h

     1 #ifndef MONGODB_H
     2 #define MONGODB_H
     3 
     4 #include <bsoncxx/builder/stream/document.hpp>
     5 #include <bsoncxx/types.hpp>
     6 #include <mongocxx/client.hpp>
     7 #include <mongocxx/instance.hpp>
     8 #include <mongocxx/uri.hpp>
     9 #include <bsoncxx/json.hpp>
    10 #include <QString>
    11 
    12 using bsoncxx::builder::stream::document;
    13 using bsoncxx::builder::stream::open_document;
    14 using bsoncxx::builder::stream::close_document;
    15 using bsoncxx::builder::stream::open_array;
    16 using bsoncxx::builder::stream::close_array;
    17 using bsoncxx::builder::stream::finalize;
    18 using namespace mongocxx;
    19 using namespace mongocxx::options;
    20 using bsoncxx::builder::basic::kvp;
    21 using bsoncxx::builder::basic::make_document;
    22 using bsoncxx::to_json;
    23 
    24 class Mongodb
    25 {
    26 protected:
    27     mongocxx::instance* m_dbInstance = nullptr;
    28     mongocxx::client* m_client = nullptr;
    29 
    30     QString m_hostName;
    31     QString m_port;
    32 
    33 public:
    34     stdx::optional<bsoncxx::document::value> find_One(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::find& options = mongocxx::v_noabi::options::find());
    35     cursor* find(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::find& options = mongocxx::v_noabi::options::find());
    36     stdx::optional<result::insert_one> insert_One(QString db,QString coll,document& doc,const mongocxx::v_noabi::options::insert& options = {});
    37     stdx::optional<result::update> update_One(QString db,QString coll,document& filter,document& value,const mongocxx::v_noabi::options::update& options = mongocxx::v_noabi::options::update());
    38     stdx::optional<result::update> update_Many(QString db,QString coll,document& filter,document& value,const mongocxx::v_noabi::options::update& options = mongocxx::v_noabi::options::update());
    39     stdx::optional<result::delete_result> delete_One(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::delete_options& options = mongocxx::v_noabi::options::delete_options());
    40     stdx::optional<result::delete_result> delete_Many(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::delete_options& options = mongocxx::v_noabi::options::delete_options());
    41     std::int64_t countDocument(QString db,QString coll,document& filter,const options::count& option = options::count());
    42 
    43 public:
    44     Mongodb();
    45     Mongodb(QString hostName,QString port);
    46     void setHostName(QString hostName);
    47     void setPort(QString port);
    48     void connectToHost();
    49     mongocxx::client* client();
    50     ~Mongodb();
    51 
    52     static QString getIDInView(const bsoncxx::v_noabi::document::view& view);
    53 };
    54 
    55 #endif // MONGODB_H

     

    Mongodb.cpp

      1 #include "Mongodb.h"
      2 #include "tinyjson.hpp"
      3 
      4 using namespace tiny;
      5 
      6 Mongodb::Mongodb()
      7 {
      8 
      9 }
     10 
     11 Mongodb::Mongodb(QString hostName,QString port)
     12 {
     13     m_hostName = hostName;
     14     m_port = port;
     15 }
     16 
     17 void Mongodb::setHostName(QString hostName)
     18 {
     19     m_hostName = hostName;
     20 }
     21 
     22 void Mongodb::setPort(QString port)
     23 {
     24     m_port = port;
     25 }
     26 
     27 void Mongodb::connectToHost()
     28 {
     29     if((m_hostName != "") && (m_port != ""))
     30     {
     31         if(m_dbInstance)
     32         {
     33             delete m_dbInstance;
     34             m_dbInstance = nullptr;
     35         }
     36 
     37         if(m_client)
     38         {
     39             delete m_client;
     40             m_client = nullptr;
     41         }
     42 
     43         m_dbInstance = new(std::nothrow) mongocxx::instance();
     44         m_client = new(std::nothrow) mongocxx::client(mongocxx::uri{("mongodb://" + m_hostName + ":" + m_port).toStdString().c_str()});
     45     }
     46 }
     47 
     48 mongocxx::client* Mongodb::client()
     49 {
     50     return m_client;
     51 }
     52 
     53 stdx::optional<bsoncxx::document::value> Mongodb::find_One(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::find& options)
     54 {
     55     stdx::optional<bsoncxx::document::value> ret;
     56 
     57     if(m_dbInstance && m_client)
     58     {
     59         return (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].find_one(filter.view(),options);
     60     }
     61 
     62     return ret;
     63 }
     64 
     65 cursor* Mongodb::find(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::find& options)
     66 {
     67     if(m_dbInstance && m_client)
     68     {
     69         auto c = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].find(filter.view(),options);
     70         return new(std::nothrow) cursor(std::move(c));
     71     }
     72 
     73     return nullptr;
     74 }
     75 
     76 stdx::optional<result::insert_one> Mongodb::insert_One(QString db,QString coll,document& doc,const mongocxx::v_noabi::options::insert& options)
     77 {
     78     stdx::optional<result::insert_one> ret;
     79 
     80     if(m_dbInstance && m_client)
     81     {
     82         ret = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].insert_one(doc.view(),options);
     83     }
     84 
     85     return ret;
     86 }
     87 
     88 stdx::optional<result::update> Mongodb::update_One(QString db,QString coll,document& filter,document& value,const mongocxx::v_noabi::options::update& options)
     89 {
     90     stdx::optional<result::update> ret;
     91     if(m_dbInstance && m_client)
     92     {
     93         ret = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].update_one(
     94                     filter.view(),
     95                     make_document(kvp("$set",value)),
     96                     options
     97                     );
     98     }
     99 
    100     return ret;
    101 }
    102 
    103 stdx::optional<result::update> Mongodb::update_Many(QString db,QString coll,document& filter,document& value,const mongocxx::v_noabi::options::update& options)
    104 {
    105     stdx::optional<result::update> ret;
    106     if(m_dbInstance && m_client)
    107     {
    108         ret = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].update_many(
    109                     filter.view(),
    110                     make_document(kvp("$set",value)),
    111                     options
    112                     );
    113     }
    114 
    115     return ret;
    116 }
    117 
    118 stdx::optional<result::delete_result> Mongodb::delete_One(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::delete_options&  options)
    119 {
    120     stdx::optional<result::delete_result> ret;
    121 
    122     if(m_dbInstance && m_client)
    123     {
    124         ret = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].delete_one(filter.view(),options);
    125     }
    126 
    127     return ret;
    128 }
    129 
    130 stdx::optional<result::delete_result> Mongodb::delete_Many(QString db,QString coll,document& filter,const mongocxx::v_noabi::options::delete_options& options)
    131 {
    132     stdx::optional<result::delete_result> ret;
    133 
    134     if(m_dbInstance && m_client)
    135     {
    136         ret = (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].delete_many(filter.view(),options);
    137     }
    138 
    139     return ret;
    140 }
    141 
    142 std::int64_t Mongodb::countDocument(QString db,QString coll,document& filter,const options::count& option)
    143 {
    144     return (*m_client)[db.toStdString().c_str()][coll.toStdString().c_str()].count_documents(filter.view(),option);
    145 }
    146 
    147 Mongodb::~Mongodb()
    148 {
    149     delete m_dbInstance;
    150     delete m_client;
    151 }
    152 
    153 QString Mongodb::getIDInView(const bsoncxx::v_noabi::document::view& view)
    154 {
    155     QString ret = "";
    156 
    157     auto str = bsoncxx::to_json(view);
    158     TinyJson json;
    159     json.ReadJson(str);
    160 
    161     auto id = json.Get<std::string>("_id");
    162     TinyJson id_json;
    163     id_json.ReadJson(id);
    164     ret = id_json.Get<std::string>("$oid").c_str();
    165 
    166     return ret;
    167 }

    tinyjson.hpp(来自github)

    https://github.com/button-chen/tinyjson

      1 /**
      2 *
      3 *    tiny::TinyJson library
      4 *    Copyright 2017 Button
      5 *
      6 */
      7 
      8 #ifndef TINY_JSON_H_
      9 #define TINY_JSON_H_
     10 
     11 #include <string>
     12 #include <sstream>
     13 #include <map>
     14 #include <vector>
     15 #include <algorithm>
     16 #include <iostream>
     17 
     18 namespace tiny {
     19 
     20     /**
     21     * 无类型,解析时确认
     22     *
     23     */
     24     class Value
     25     {
     26     public:
     27         Value() {
     28             value_.clear();
     29             nokey_ = false;
     30         }
     31         Value(std::string val) : value_(val) {
     32             if (value_ == "") {
     33                 value_.clear();
     34                 nokey_ = true;
     35             }
     36             else {
     37                 nokey_ = false;
     38             }
     39         }
     40         ~Value() {}
     41 
     42     public:
     43         std::string value() { return value_; }
     44         template<typename R> 
     45         R GetAs() {
     46             std::istringstream iss(value_);
     47             R v;
     48             iss >> v;
     49             return v;
     50         }
     51 
     52 
     53         template<typename V> 
     54         void Set(V v) {
     55             std::ostringstream oss;
     56             if (nokey_) {
     57                 oss << v;
     58             }
     59             else {
     60                 oss << """ << value_ << """ << ":" << v;
     61             }
     62             value_ = oss.str();
     63         }
     64 
     65         template<typename T>
     66         void Push(T& v) {
     67             std::ostringstream oss;
     68             if (v.get_nokey()) {
     69                 oss << v.WriteJson(0);
     70             }
     71             else {
     72                 oss << v.WriteJson(1);
     73             }
     74             value_ = oss.str();
     75         }
     76 
     77     private:
     78         std::string value_;
     79         bool nokey_;
     80     };
     81 
     82         template<> inline bool Value::GetAs() { return value_ == "true" ? true : false; }
     83         template<> inline std::string Value::GetAs() { return value_; }
     84         template<>
     85         inline void Value::Set(std::string v) {
     86                 std::ostringstream oss;
     87                 if (nokey_) {
     88                         oss << """ << v << """;
     89                 }
     90                 else {
     91                         oss << """ << value_ << """ << ":" << """ << v << """;
     92                 }
     93                 value_ = oss.str();
     94         }
     95 
     96         template<>
     97         inline void Value::Set(const char* v) {
     98                 Set(std::string(v));
     99         }
    100 
    101         template<>
    102         inline void Value::Set(bool v) {
    103                 std::ostringstream oss;
    104                 std::string val = v == true ? "true" : "false";
    105                 if (nokey_) {
    106                         oss << val;
    107                 }
    108                 else {
    109                         oss << """ << value_ << """ << ":" << val;
    110                 }
    111                 value_ = oss.str();
    112         }
    113 
    114     /**
    115     * 此模板类处理json键对应的值是一个嵌套对象或者数组的情况
    116     * 
    117     */
    118     template<typename T>
    119     class ValueArray : public T
    120     {
    121     public:
    122         ValueArray() {}
    123         ValueArray(std::vector<std::string> vo) { vo_ = vo; }
    124 
    125         bool Enter(int i) {
    126             std::string obj = vo_[i];
    127                         return this->ReadJson(obj);
    128         }
    129 
    130         int Count() { return vo_.size(); }
    131 
    132     private:
    133         std::vector<std::string> vo_;
    134     };
    135 
    136     /**
    137     * 解析json字符串保存为键值的顺序存储,解析是按一层一层的进行
    138     * 解析时把json看做是对象'{}' 与 数组'[]' 的组合
    139     *
    140     */
    141     class ParseJson
    142     {
    143     public:
    144         ParseJson() {}
    145         ~ParseJson() {}
    146 
    147     public:
    148         bool ParseArray(std::string json, std::vector<std::string>& vo);
    149         bool ParseObj(std::string json);
    150         std::vector<std::string> GetKeyVal() {
    151             return keyval_;
    152         }
    153 
    154     protected:
    155         std::string Trims(std::string s, char lc, char rc);
    156         int GetFirstNotSpaceChar(std::string& s, int cur);
    157         std::string FetchArrayStr(std::string inputstr, int inpos, int& offset);
    158         std::string FetchObjStr(std::string inputstr, int inpos, int& offset);
    159         std::string FetchStrStr(std::string inputstr, int inpos, int& offset);
    160         std::string FetchNumStr(std::string inputstr, int inpos, int& offset);
    161 
    162     private:
    163         std::vector<char> token_;
    164         std::vector<std::string> keyval_;
    165     };
    166 
    167     inline bool ParseJson::ParseArray(std::string json, std::vector<std::string>& vo) {
    168         json = Trims(json, '[', ']');
    169         std::string tokens;
    170         size_t i = 0;
    171         for (; i < json.size(); ++i) {
    172             char c = json[i];
    173             if (isspace(c) || c == '"') continue;
    174             if (c == ':' || c == ',' || c == '{') {
    175                 if (!tokens.empty()) {
    176                     vo.push_back(tokens);
    177                     tokens.clear();
    178                 }
    179                 if (c == ',') continue;
    180                 int offset = 0;
    181                 char nextc = c;
    182                 for (; c != '{';) {
    183                     nextc = json[++i];
    184                     if (isspace(nextc)) continue;
    185                     break;
    186                 }
    187                 if (nextc == '{') {
    188                     tokens = FetchObjStr(json, i, offset);
    189                 }
    190                 else if (nextc == '[') {
    191                     tokens = FetchArrayStr(json, i, offset);
    192                 }
    193                 i += offset;
    194                 continue;
    195             }
    196             tokens.push_back(c);
    197         }
    198         if (!tokens.empty()) {
    199             vo.push_back(tokens);
    200         }
    201         return true;
    202     }
    203 
    204     // 解析为 key-value 调用一次解析一个层次
    205     inline bool ParseJson::ParseObj(std::string json) {
    206         auto LastValidChar = [&](int index)->char{
    207             for (int i = index-1; i >= 0; --i){
    208                 if (isspace(json[i])) continue;
    209                 char tmp = json[i];
    210                 return tmp;
    211             }
    212             return '';
    213         };
    214 
    215         json = Trims(json, '{', '}');
    216         size_t i = 0;
    217         for (; i < json.size(); ++i) {
    218             char nextc = json[i];
    219             if (isspace(nextc)) continue;
    220 
    221             std::string tokens;
    222             int offset = 0;
    223             if (nextc == '{') {
    224                 tokens = FetchObjStr(json, i, offset);
    225             }
    226             else if (nextc == '[') {
    227                 tokens = FetchArrayStr(json, i, offset);
    228             }
    229             else if (nextc == '"') {
    230                 tokens = FetchStrStr(json, i, offset);
    231             }
    232             else if (isdigit(nextc) && LastValidChar(i) == ':')
    233             {
    234                 tokens = FetchNumStr(json, i, offset);
    235             }
    236             else {
    237                 continue;
    238             }
    239             keyval_.push_back(tokens);
    240             i += offset;
    241         }
    242         if (keyval_.size() == 0)
    243         {
    244             keyval_.push_back(json);
    245         }
    246         return true;
    247     }
    248 
    249     inline std::string ParseJson::Trims(std::string s, char lc, char rc)
    250     {
    251         std::string ss = s;
    252         if (s.find(lc) != std::string::npos && s.find(rc) != std::string::npos) {
    253             size_t b = s.find_first_of(lc);
    254             size_t e = s.find_last_of(rc);
    255             ss = s.substr(b + 1, e - b - 1);
    256         }
    257         return ss;
    258     }
    259 
    260     inline int ParseJson::GetFirstNotSpaceChar( std::string& s, int cur )
    261     {
    262         for (size_t i = cur; i < s.size(); i++){
    263             if (isspace(s[i])) continue;
    264             return i - cur;
    265         }
    266         return 0;
    267     }
    268 
    269     inline std::string ParseJson::FetchArrayStr(std::string inputstr, int inpos, int& offset)
    270     {
    271         int tokencount = 0;
    272         std::string objstr;
    273         size_t i = inpos + GetFirstNotSpaceChar(inputstr, inpos);
    274         for (; i < inputstr.size(); i++) {
    275             char c = inputstr[i];
    276             if (c == '[') {
    277                 ++tokencount;
    278             }
    279             if (c == ']') {
    280                 --tokencount;
    281             }
    282             objstr.push_back(c);
    283             if (tokencount == 0) {
    284                 break;
    285             }
    286         }
    287         offset = i - inpos;
    288         return objstr;
    289     }
    290 
    291     inline std::string ParseJson::FetchObjStr(std::string inputstr, int inpos, int& offset)
    292     {
    293         int tokencount = 0;
    294         std::string objstr;
    295         size_t i = inpos + GetFirstNotSpaceChar(inputstr, inpos);
    296         for (; i < inputstr.size(); i++) {
    297             char c = inputstr[i];
    298             if (c == '{') {
    299                 ++tokencount;
    300             }
    301             if (c == '}') {
    302                 --tokencount;
    303             }
    304             objstr.push_back(c);
    305             if (tokencount == 0) {
    306                 break;
    307             }
    308         }
    309         offset = i - inpos;
    310         return objstr;
    311     }
    312 
    313     inline std::string ParseJson::FetchStrStr( std::string inputstr, int inpos, int& offset )
    314     {
    315         int tokencount = 0;
    316         std::string objstr;
    317         size_t i = inpos + GetFirstNotSpaceChar(inputstr, inpos);
    318         for (; i < inputstr.size(); i++) {
    319             char c = inputstr[i];
    320             if (c == '"') {
    321                 ++tokencount;
    322             }
    323             objstr.push_back(c);
    324             if (tokencount % 2 == 0 && (c == ',' || c == ':')) {
    325                 break;
    326             }
    327         }
    328         offset = i - inpos;
    329 
    330         return Trims(objstr, '"', '"');
    331     }
    332 
    333     inline std::string ParseJson::FetchNumStr( std::string inputstr, int inpos, int& offset )
    334     {
    335         std::string objstr;
    336         size_t i = inpos + GetFirstNotSpaceChar(inputstr, inpos);
    337         for (; i < inputstr.size(); i++) {
    338             char c = inputstr[i];
    339             if (c == ',') {
    340                 break;
    341             }
    342             objstr.push_back(c);
    343         }
    344         offset = i - inpos;
    345 
    346         return objstr;
    347     }
    348 
    349     /**
    350     * 对外接口类
    351     *
    352     */
    353     class TinyJson;
    354     typedef ValueArray<TinyJson> xarray;
    355     typedef ValueArray<TinyJson> xobject;
    356 
    357     class TinyJson
    358     {
    359         friend class ValueArray<TinyJson>;
    360     public:
    361         TinyJson() {
    362             nokey_ = false;
    363         }
    364         ~TinyJson() {}
    365 
    366     public:
    367         // read
    368         bool ReadJson(std::string json) {
    369             ParseJson p;
    370             p.ParseObj(json);
    371             KeyVal_ = p.GetKeyVal();
    372             return true;
    373         }
    374 
    375         template<typename R>
    376         R Get(std::string key, R defVal) {
    377             auto itr = std::find(KeyVal_.begin(), KeyVal_.end(), key);
    378             if (itr == KeyVal_.end()) {
    379                 return defVal;
    380             }
    381             return Value(*(++itr)).GetAs<R>();
    382         }
    383 
    384         template<typename R>
    385         R Get(std::string key) {
    386             return Get(key, R());
    387         }
    388 
    389         template<typename R>
    390         R Get() {
    391             return Value(KeyVal_[0]).GetAs<R>();
    392         }
    393 
    394         // write
    395         Value& operator[](std::string k) {
    396             Items_.push_back(Value(k));
    397             Value& v = Items_[Items_.size() - 1];
    398             if (k == "") {
    399                 nokey_ = true;
    400             }
    401             return v;
    402         }
    403 
    404         void Push(TinyJson item) {
    405             Items_.push_back(Value(""));
    406             Value& v = Items_[Items_.size() - 1];
    407             nokey_ = true;
    408             v.Push(item);
    409             sub_type_ = 1;
    410         }
    411 
    412         bool get_nokey() {
    413             return nokey_;
    414         }
    415 
    416         std::string WriteJson(){
    417             return WriteJson(1);
    418         }
    419 
    420         // 0: none  1: object  2: array
    421         std::string WriteJson(int type);
    422 
    423     public:
    424         int sub_type_;
    425 
    426     private:
    427         std::vector<std::string> KeyVal_;
    428         std::vector<Value> Items_;
    429         bool nokey_;
    430     };
    431 
    432     template<>
    433     inline xarray TinyJson::Get(std::string key) {
    434         std::string val = Get<std::string>(key);
    435         ParseJson p;
    436         std::vector<std::string> vo;
    437         p.ParseArray(val, vo);
    438         xarray vals(vo);
    439         return vals;
    440     }
    441 
    442     inline std::ostream & operator << (std::ostream& os, TinyJson& ob)
    443     {
    444         os << ob.WriteJson();
    445         return os;
    446     }
    447 
    448     inline std::string TinyJson::WriteJson(int type)
    449     {
    450         std::string prefix = type == 1 ? "{" : "[";
    451         std::string suffix = type == 1 ? "}" : "]";
    452         if (type == 0) {
    453             prefix = "";
    454             suffix = "";
    455         }
    456         std::ostringstream oss;
    457         oss << prefix;
    458         int i = 0;
    459         int size = Items_.size();
    460         std::string seq = ",";
    461         for (; i < size; ++i) {
    462             Value& v = Items_[i];
    463             oss << v.value() << seq;
    464         }
    465         std::string jsonstring = oss.str();
    466         if (jsonstring.back() == ',') {
    467             jsonstring = jsonstring.substr(0, jsonstring.find_last_of(','));
    468         }
    469 
    470         jsonstring += suffix;
    471         return jsonstring;
    472     }
    473 
    474     template<>
    475     inline void Value::Set(TinyJson v) {
    476         std::ostringstream oss;
    477         if (v.sub_type_ == 1) {
    478             oss << """ << value_ << """ << ":" << v.WriteJson(2);
    479         }
    480         else {
    481             if (nokey_) {
    482                 oss << v;
    483             }
    484             else {
    485                 oss << """ << value_ << """ << ":" << v;
    486             }
    487         }
    488         value_ = oss.str();
    489     }
    490 
    491 }  // end namesapce
    492 
    493 #endif  // TINY_JSON_H_

    tinyjson使用案例

      1 #pragma once
      2 
      3 #include "tinyjson.hpp"
      4 #include <string>
      5 #include <iostream>
      6 #include <cassert>
      7 using namespace std;
      8 using namespace tiny;
      9 
     10 string jsonstring = "
     11 {
     12     "name":"lier  gou",
     13     "age" : 26.9,
     14     "data" : [
     15     {
     16         "one":"chenone",
     17         "two" : {
     18             "love1":"2233",
     19             "love2":44444
     20         }
     21     },
     22     {
     23         "one":"chen22",
     24         "two" : {
     25             "love1":"8899",
     26             "love2":10000
     27         }
     28     }
     29     ],
     30     "lang":"2cpp"
     31 }
     32 ";
     33 
     34 string jsonstring2 = "
     35 {
     36     "name":"liergou",
     37     "age" : 26.9,
     38     "data" : [
     39     {
     40         "one":"chenone",
     41         "two" : [
     42             "love_chen",
     43             "love_hui"
     44         ]
     45     },
     46     {
     47         "one":"chen22",
     48         "two" : [
     49             "love_chen2",
     50             "love_hui2"
     51         ]
     52     }
     53     ],
     54     "lang":"cpp"
     55 }
     56 ";
     57 
     58 string jsonstring3 = "
     59 {
     60     "xx": {
     61         "a": 1,
     62         "b" : 2
     63     }
     64 }";
     65 
     66 // read demo
     67 void TEST99() {
     68     cout << "
    TEST 99 READ JSON" << endl;
     69     // read
     70     TinyJson json;
     71     json.ReadJson(jsonstring3);
     72 
     73     xobject data = json.Get<xobject>("xx");
     74     for (int i = 0; i < data.Count(); i++) {
     75         data.Enter(i);
     76         int one = data.Get<int>("a");
     77         int two = data.Get<int>("b");
     78         int three = data.Get<int>("c", 99);
     79         assert(one == 1);
     80         assert(two == 2);
     81         assert(three == 99);
     82     }
     83     cout << "TEST 99 PASS" << endl;
     84 }
     85 
     86 
     87 // read demo
     88 void TEST1() {
     89     cout << "
    TEST 1 READ JSON" << endl;
     90     // read
     91     TinyJson json;
     92     json.ReadJson(jsonstring);
     93 
     94     string name = json.Get<string>("name");
     95     float age = json.Get<float>("age");
     96     string lang = json.Get<string>("lang");
     97 
     98     assert(name == "lier  gou");
     99     assert(age > 26 && age < 27);
    100     assert(lang == "2cpp");
    101 
    102     xarray data = json.Get<xarray>("data");
    103     for (int i = 0; i < data.Count(); i++) {
    104         data.Enter(i);
    105         string one = data.Get<string>("one");
    106         if (i == 0)
    107         {
    108             assert(one == "chenone");
    109         }
    110         if (i == 1)
    111         {
    112             assert(one == "chen22");
    113         }
    114         xobject two = data.Get<xobject>("two");
    115         for (int ii = 0; ii < two.Count(); ii++) {
    116             two.Enter(ii);
    117             string love1 = two.Get<string>("love1");
    118             int love2 = two.Get<int>("love2");
    119             if (i == 0)
    120             {
    121                 assert(love1 == "2233");
    122                 assert(love2 == 44444);
    123             }
    124             if (i == 1)
    125             {
    126                 assert(love1 == "8899");
    127                 assert(love2 == 10000);
    128             }
    129 
    130         }
    131     }
    132     cout << "TEST 1 PASS" << endl;
    133 }
    134 
    135 // read demo
    136 void TEST2() {
    137     cout << "
    TEST 2 READ JSON" << endl;
    138     // read
    139     TinyJson json;
    140     json.ReadJson(jsonstring2);
    141 
    142     string name = json.Get<string>("name");
    143     float age = json.Get<float>("age");
    144     string lang = json.Get<string>("lang");
    145 
    146     assert(name == "liergou");
    147     assert(age > 26 && age < 27);
    148     assert(lang == "cpp");
    149 
    150     xarray data = json.Get<xarray>("data");
    151     for (int i = 0; i < data.Count(); i++) {
    152         data.Enter(i);
    153         string one = data.Get<string>("one");
    154         if (i == 0)
    155         {
    156             assert(one == "chenone");
    157         }
    158         if (i == 1)
    159         {
    160             assert(one == "chen22");
    161         }
    162         xarray two = data.Get<xarray>("two");
    163         for (int ii = 0; ii < two.Count(); ii++) {
    164             two.Enter(ii);
    165             string val = two.Get<string>();
    166             if (i == 0 && ii == 0)
    167             {
    168                 assert(val == "love_chen");
    169             }
    170             if (i == 0 && ii == 1)
    171             {
    172                 assert(val == "love_hui");
    173             }
    174             if (i == 1 && ii == 0)
    175             {
    176                 assert(val == "love_chen2");
    177             }
    178             if (i == 1 && ii == 1)
    179             {
    180                 assert(val == "love_hui2");
    181             }
    182         }
    183     }
    184     cout << "TEST 2 PASS" << endl;
    185 }
    186 
    187 // write demo TEST3()
    188 
    189 /*   write result
    190 
    191 {
    192     "name": "liergou",
    193     "age": 26,
    194     "handsome": true,
    195     "data": {
    196         "love1": "book",
    197         "love2": 666
    198     },
    199     "data2": {
    200         "love1": "book2",
    201         "love2": 6662
    202     }
    203 }
    204 
    205 */
    206 
    207 void TEST3() {
    208     cout << "
    TEST 3 WRITE JSON" << endl;
    209     // write
    210     TinyJson wjson;
    211     wjson["name"].Set("liergou");
    212     wjson["age"].Set(26);
    213     wjson["handsome"].Set(true);
    214 
    215     TinyJson subjson;
    216     subjson["love1"].Set("book");
    217     subjson["love2"].Set(666);
    218 
    219     TinyJson subjson2;
    220     subjson2["love1"].Set("book2");
    221     subjson2["love2"].Set(6662);
    222 
    223     wjson["data"].Set(subjson);
    224     wjson["data2"].Set(subjson2);
    225 
    226     string str = wjson.WriteJson();
    227     cout << "json string: 
    " << endl;
    228     cout << str << endl;
    229 }
    230 
    231 // write demo TEST4()
    232 
    233 /*   write result
    234 
    235 {
    236     "name": "liergou",
    237     "age" : 26,
    238     "handsome" : true,
    239     "data" : [
    240       {
    241         "love1": "book",
    242         "love2" : 666
    243       },
    244       {
    245         "love1": "book2",
    246         "love2" : 6662
    247       }
    248     ]
    249 }
    250 
    251 */
    252 
    253 void TEST4() {
    254     cout << "
    TEST 4 WRITE JSON" << endl;
    255     // write
    256     TinyJson wjson;
    257     wjson["name"].Set("liergou");
    258     wjson["age"].Set(26);
    259     wjson["handsome"].Set(true);
    260 
    261     TinyJson subjson;
    262     subjson["love1"].Set("book");
    263     subjson["love2"].Set(666);
    264 
    265     TinyJson subjson2;
    266     subjson2["love1"].Set("book2");
    267     subjson2["love2"].Set(6662);
    268 
    269     TinyJson jsonarray;
    270     jsonarray.Push(subjson);
    271     jsonarray.Push(subjson2);
    272 
    273     wjson["data"].Set(jsonarray);
    274 
    275     string str = wjson.WriteJson();
    276     cout << "json string: 
    " << endl;
    277     cout << str << endl;
    278 }
    279 
    280 // write demo TEST5()
    281 
    282 /*   write result
    283 
    284 {
    285     "name": "liergou",
    286     "age" : 26,
    287     "handsome" : true,
    288     "data" : [
    289          "book",
    290          666
    291     ]
    292 }
    293 
    294 */
    295 
    296 void TEST5() {
    297     cout << "
    TEST 5 WRITE JSON" << endl;
    298     // write
    299     TinyJson wjson;
    300     wjson["name"].Set("liergou");
    301     wjson["age"].Set(26);
    302     wjson["handsome"].Set(true);
    303 
    304     TinyJson subjson;
    305     subjson[""].Set("book");
    306     subjson[""].Set(666);
    307 
    308     TinyJson jsonarray;
    309     jsonarray.Push(subjson);
    310 
    311     wjson["data"].Set(jsonarray);
    312 
    313     string str = wjson.WriteJson();
    314     cout << "json string: 
    " << endl;
    315     cout << str << endl;
    316 }
  • 相关阅读:
    html 复选框
    html 单选框
    C++创建类的对象(类的初始化)的方法
    C++创建类的对象(类的初始化)的方法
    C#基础实现URL Unicode编码,编码、解码相关整理
    C#基础实现URL Unicode编码,编码、解码相关整理
    js 发送http请求
    js 发送http请求
    C++的三种实例化对象方式
    C++的三种实例化对象方式
  • 原文地址:https://www.cnblogs.com/liweikuan/p/14375563.html
Copyright © 2020-2023  润新知