#include <json_spirit.h> const std::string test = "{" " \"text\": \"Home-plate umpire Crawford gets stung http://tinyurl.com/27ujc86\"," " \"favorited\": false," " \"source\": \"<a href=\\\"http://apiwiki.twitter.com/\\\" rel=\\\"nofollow\\\">API</a>\"," " \"user\": {" " \"name\": \"Johnathan Thomas\"" " }" "}"; int main() { namespace js = json_spirit; js::mValue top; js::read(std::string(test), top); json_spirit::mObject obj = top.get_obj(); std::cout << "--------" << std::endl; std::cout << obj["text" ].get_str() << "\n" << obj["favorited"].get_bool() << "\n" << obj["source" ].get_str() << "\n" << obj["user" ].get_obj()["name"].get_str() << "\n"; }
#include <db/json.h> // load fromjson method #include <iostream> #include <string> const std::string test = "{ \"specs\" : " " [ {\"id\":\"value1\" , \"name\":\"jack\"}," " {\"id\": \"value2\", \"name\":\"jack2\"}," "{\"id\": \"value3\", \"name\":\"jack3\"}" " ]" "}"; int main() { try{ // { "specs" : [ {"id":"value1" , "name":"jack"}, {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]} std::cout << "Test json string:" << test << std::endl; // parse json method from json.h file // throws MsgAssertionException if parsing fails. The message included with // this assertion includes a rough indication of where parsing failed. mongo::BSONObj obj = mongo::fromjson(test); mongo::BSONObj eles = obj["specs"].Obj(); // get array obj /** add all values of the object to the specified vector. If type mismatches, exception. this is most useful when the BSONObj is an array, but can be used with non-arrays too in theory. example: bo sub = y["subobj"].Obj(); vector<int> myints; sub.Vals(myints); */ vector<mongo::BSONObj> specs; eles.Vals(specs); // print values for(int i = 0; i < 3; ++i) std::cout << specs.at(i)["id"].String() << ":" << specs.at(i)["name"].String()<< endl; } catch(const mongo::MsgAssertionException& e) { std::cout << "parse exception " << e.what() << endl; } }
运行结果:
gxl@gxl-desktop:~/Test_place$ g++ sample.cpp -o sample -I/usr/local/include/mongo/ -lmongoclient gxl@gxl-desktop:~/Test_place$ ./sample Test json string:{ "specs" : [ {"id":"value1" , "name":"jack"}, {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]} value1:jack value2:jack2 value3:jack3