如何使用MongoDB自带的json库来反序列json字符串
需求:
在对mongodb中的字段值进行解析的时候发现,因为这个值是json字符串,需要对其进行反序列化。解决方法:
首先想到了到http://www.json.org/json-zh.html网站去找相应的C++库,试了一下jsoncpp和JSON Spirit,因为是用scons来构建了,装了一下,编译以后玩不起来,放弃了。再试JSON Spirit,(http://www.codeproject.com/Articles/20027/JSON-Spirit-A-C-JSON-Parser-Generator-Implemented), 这东东不错,好像是依赖于Boost Spirit的,这个我也装了,安装过程还是满方便的,因为我的C++项目都是用CMake的,这个也是用它的,所以编译安装没有遇到什么问题。下面给出一个相应的例子:#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() << " " << obj["favorited"].get_bool() << " " << obj["source" ].get_str() << " " << obj["user" ].get_obj()["name"].get_str() << " "; }
下面想到了mongodb有自己的bson结构,这个东东和json是差不多的,在mongodb的源代码包里找到了json.h这个文件看,盾到了fromjson这个方法,看来能行。呵呵
下面是我的测试代码,因为我的value中用到了array,这里还用到了别外一个把BSONObj转换成Array<BSONObj>的方法。
#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
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 利用反射实现简单的Class对象和Bson文档的转换
- 下一篇: BSON与JSON