如何使用MongoDB自带的json库来反序列json字符串

来源:互联网 发布:mysql分类汇总 编辑:程序博客网 时间:2024/05/01 20:57

如何使用MongoDB自带的json库来反序列json字符串

标签: jsonmongodbparsingstringexceptionuser
 6170人阅读 评论(0) 收藏 举报
 分类:
 

目录(?)[+]


需求:

在对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的,这个也是用它的,所以编译安装没有遇到什么问题。下面给出一个相应的例子:

[cpp] view plain copy
  1. #include <json_spirit.h>  
  2.   
  3. const std::string test =  
  4. "{"  
  5. "    \"text\": \"Home-plate umpire Crawford gets stung http://tinyurl.com/27ujc86\","  
  6. "    \"favorited\": false,"  
  7. "    \"source\": \"<a href=\\\"http://apiwiki.twitter.com/\\\" rel=\\\"nofollow\\\">API</a>\","  
  8. "    \"user\": {"  
  9. "        \"name\": \"Johnathan Thomas\""  
  10. "    }"  
  11. "}";  
  12.   
  13.   
  14. int main() {  
  15.     namespace js = json_spirit;  
  16.     js::mValue top;  
  17.     js::read(std::string(test), top);  
  18.     json_spirit::mObject obj = top.get_obj();  
  19.     std::cout << "--------" << std::endl;  
  20.       
  21.     std::cout   
  22.       << obj["text"     ].get_str()  << "\n"  
  23.       << obj["favorited"].get_bool() << "\n"  
  24.       << obj["source"   ].get_str()  << "\n"  
  25.       << obj["user"     ].get_obj()["name"].get_str() << "\n";  
  26. }  

下面想到了mongodb有自己的bson结构,这个东东和json是差不多的,在mongodb的源代码包里找到了json.h这个文件看,盾到了fromjson这个方法,看来能行。呵呵
下面是我的测试代码,因为我的value中用到了array,这里还用到了别外一个把BSONObj转换成Array<BSONObj>的方法。


[cpp] view plain copy
  1. #include <db/json.h>   // load fromjson method  
  2.   
  3. #include <iostream>  
  4. #include <string>  
  5. const std::string test =  
  6.     "{ \"specs\" : "  
  7.     " [ {\"id\":\"value1\" , \"name\":\"jack\"},"  
  8.     "   {\"id\": \"value2\", \"name\":\"jack2\"},"  
  9.     "{\"id\": \"value3\", \"name\":\"jack3\"}"  
  10.     " ]"  
  11.     "}";  
  12.   
  13.   
  14. int main()  
  15. {  
  16.     try{  
  17.         // { "specs" :  [ {"id":"value1" , "name":"jack"},   {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]}  
  18.         std::cout << "Test json string:" << test << std::endl;  
  19.   
  20.   
  21.         // parse json method from json.h file  
  22.         // throws MsgAssertionException if parsing fails.  The message included with  
  23.         // this assertion includes a rough indication of where parsing failed.  
  24.         mongo::BSONObj obj = mongo::fromjson(test);  
  25.         mongo::BSONObj eles = obj["specs"].Obj();   // get array obj  
  26.   
  27.   
  28.         /** add all values of the object to the specified vector.  If type mismatches, exception. 
  29.             this is most useful when the BSONObj is an array, but can be used with non-arrays too in theory. 
  30.  
  31.  
  32.             example: 
  33.               bo sub = y["subobj"].Obj(); 
  34.               vector<int> myints; 
  35.               sub.Vals(myints); 
  36.         */  
  37.   
  38.   
  39.         vector<mongo::BSONObj> specs;  
  40.         eles.Vals(specs);  
  41.   
  42.   
  43.         // print values  
  44.         for(int i = 0; i < 3; ++i)  
  45.             std::cout << specs.at(i)["id"].String() << ":" <<  specs.at(i)["name"].String()<< endl;  
  46.     }  
  47.     catch(const mongo::MsgAssertionException& e)  
  48.     {  
  49.         std::cout << "parse exception " << e.what() << endl;  
  50.     }  
  51. }  


运行结果:

[plain] view plain copy
  1. gxl@gxl-desktop:~/Test_place$ g++ sample.cpp -o sample -I/usr/local/include/mongo/ -lmongoclient  
  2. gxl@gxl-desktop:~/Test_place$ ./sample   
  3. Test json string:{ "specs" :  [ {"id":"value1" , "name":"jack"},   {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]}  
  4. value1:jack  
  5. value2:jack2  
  6. value3:jack3 
0 0