C++序列化和反序列化

C++序列化:

hello.cpp  中代码:

 1 #include <cppcms/json.h>  
2 #include <iostream>
3
4 using namespace std;
5
6 class response {
7 public:
8 //0 is ok
9 //other values are wrong
10 int status;
11 string message;
12 };
13 namespace cppcms {
14 namespace json {
15
16 template<>
17 struct traits<response> {
18
19 static void set(value &v, response const& in) {
20 v.set("status", in.status);
21 v.set("message", in.message);
22 }
23 };
24
25 }
26 }
27
28 int main(int argc, char** argv) {
29 response r1;
30 r1.status=0;
31 r1.message="ok";
32 cout<< cppcms::json::value(r1)<<endl;
33
34 response r2;
35 r2.status=1;
36 r2.message="unknown error";
37 cout<< cppcms::json::value(r2)<<endl;
38 return 0;
39 }

运行结果:

前提:安装CppCMS

C++反序列化:

fhello.cpp 中代码:

 1 #include <cppcms/json.h>  
2 #include <iostream>
3 #include <sstream>
4 using namespace std;
5 int main(int argc, char** argv) {
6 istringstream stream("{\"message\":\"ok\",\"status\":0}");
7
8 cppcms::json::value value2;
9 stream >> value2;
10 string m = value2.get("message","null");
11 int n = value2.get("status",1);
12 cout << "message:" << m << endl;
13 cout << "status:" << n << endl;
14 return 0;
15 }

运行结果:

参考:http://blog.csdn.net/sheismylife/article/details/7096228
        http://cppcms.com/wikipp/en/page/cppcms_1x_tut_hello



posted @ 2012-03-21 15:18  雨中枫叶  阅读(8451)  评论(0编辑  收藏  举报