Http://blog.csdn.net/vagrxie/archive/2010/07/23/5754179.aspx
{2009 11 09}
C ++ uses JSON for data packaging format Communication
Copyright Disclaimer: During reprinting, please use hyperlinks to indicate the original source and author information of the article.
Link: http://adebugger.cn/2009/11/cpp-json-data-communication/
JSON is familiar to everyone, right? JSON is widely used for communication, especially HTTP-based communication. Generally, the server dynamic scripting language has a library that supports JSON encoding and decoding. But few have heard that JSON is used by C ++ as the communication format.
As described on the homepage of jsoncpp, jsoncpp is an encoding decoder in JSON data format. It provides reader and writer for decoding and encoding. The following is a brief introduction to jsoncpp:
1. Reader
The reader class in this library is used to load strings or streams into the parser. Yes, the parsing method in Reader can be used later to decode the data recognized by C ++ as the JSON string. You can use JSON: reader to declare a reader instance. The most common method in reader is the parse method, which is used to parse the loaded JSON string into data in C ++ format.
2. Value
This is the core class in this library. It is used to store data in various formats, including int, double, short, char *, String, bool, object, array, and other data in almost all formats. The core functions of the library encoding and decoding are implemented using the value class. In the preceding parse method of reader, you need to input a reference value of the value category to store the root value of JSON data, you can use this root value to access all other values.
3. Writer
This is a virtual class of the library and does not actually implement the encode function. You need to reload the methods to implement the real encode function.
4. fastwriter
This is the class that truly implements the encode function in the library and is used to call value Encoding As a JSON string.
I am currently using these classes. This Library also provides functions for processing JSON string comments and styles to format JSON strings, which are easier to read, and then share it later. The following uses a short piece of code to view the basic functions of the above jsoncpp:
C ++ language:
01 /*
02 this function to encode game/play message
03! In
04 token: token string
05 game_id: Game ID
06 piece_array: piece Array
07
08! Out
09 encoded JSON string of GAME/play message
10
11! Example:
12 token = "ASDFASDF"
13 game_id = 1;
14 piece_array = [{'A', true,}, {'A ', true, 3, 4}]
15
16 return:
17 [{"game_id": 1, "piece_array": [{"letter": 65, "wild": True, "x": 0, "Y": 1 }, {"letter": 65,
18 "wild": True, "x": 1, "Y": 2 },{ "letter": 65, "wild": True, "x": 2, "Y": 3 },{ "letter": 65, "wil
19 D ": True," x ": 3," Y ": 4 },{" letter ": 65," wild ": True," x ": 4, "Y": 5}], "token": "ASDFASDF"}]
20 */
21 string encode_game_play_msg (string token, int game_id, vector piece_array ){
22 JSON: Value root;
23 JSON: Value var;
24
25 // apply "token" and "game_id" value to JSON struct
26 var ["token"] = token;
27 var ["game_id"] = game_id;
28
29 JSON: Value pieces; // store all pieces
30 For (INT I = 0; I <piece_array.size (); I ++)
31 {
32 JSON: Value piece_ex; // here it store just one piece
33
34 // next 4 lines to apply piece value to JSON struct
35 piece_ex ["letter"] = piece_array [I]. letter;
36 piece_ex ["wild"] = piece_array [I]. Wild;
37 piece_ex ["X"] = piece_array [I]. X;
38 piece_ex ["Y"] = piece_array [I]. Y;
39 pieces. append (piece_ex); // OK, yes we just have apply one piece, then push back to the array
40}
41 var ["piece_array"] = pieces; // Yes, store pieces in Var [value]
42 root. append (VAR );
43
44 JSON: fastwriter writer;
45 return writer. Write (VAR); // generate JSON string :), here all is done
46}
The above Code uses most of the jsoncpp encoding functions to call data encoding a JSON string. The following will carefully analyze this code.
1. First, please refer to the notes! In, which is the input parameter of this function. There are three tokens of the string type, one is the game_id of the int type, and the other is the array used to store all piece. Look! The out part is the JSON string to be output. The following output shows that the JSON string contains a large root object with three items: 1. Token, 2. game_id, 3. piece_array.
2. encode Process
As mentioned before, value is the core class in jsoncpp, and both Reader and writer use the value function. The above Code includes the [] operator to assign values to values. value should be a data warehouse similar to a map structure, used to store all data in the tree, and finally converted to a string encoded in JSON format. In the process of encoding the array, value provides an append function to be appended to the value. Remember to say that value can be directly stored in the array. Of course, the [] Operator of value cannot directly use an array as a parameter. If so, you can. C ++ compilation languages cannot be so dynamic, so we can see that the code is actually nested with value, and value is used to assign values to an array element, array elements are not a simple internal type supported by the compiler, so they need to be undefined.
3. encode
Finally, fastwriter is directly used to encode the output. This is a typical jsoncpp JSON encoding process.
Let's take a look at the code for decoding the JSON string.
C ++ language:
01 /*
02 This function decode lolobby/data return message
03! Example
04 lolobby data JSON string:
05 {/"game /":{/
06/"ID/": 1 ,/
07/"creator_id/": 2 ,/
08/"user_max/": 500 ,/
09/"template/": {/"ID/": 1 },/
10/"user_array /":[/
11 {/"ID/": 1,/"name/":/"test1 /"},/
12 {/"ID/": 2,/"name/":/"Test2 /"},/
13 {/"ID/": 3,/"name/":/"test3 /"},/
14 {/"ID/": 4,/"name/":/"test4 /"},/
15 {/"ID/": 5,/"name/":/"test5 /"},/
16 {/"ID/": 6,/"name/":/"test6 /"},/
17 {/"ID/": 7,/"name/":/"test7 /"},/
18 {/"ID/": 8,/"name/":/"test8 /"},/
19 {/"ID/": 9,/"name/":/"test9 /"}/
20]/
21 }}
22 this function will return a [game_info] structure to be filled by parsed result
23 game_info gi;
24 gi. ID-> 1
25 gi. creator_id-> 2
26 gi. user_max-> 500
27 gi. template_r.id-> 1
28 gi. user_array-> [{1, "test1"}, {2, "Test2"}...] // This Is A user_info array to store the game's users
29 */
30 game_info decode_lobby_data_return_msg (string lobby_data_return_msg ){
31 JSON: Value root;
32 JSON: reader;
33 game_info gi;
34 bool parsedok = false;
35 parsedok = reader. parse (lobby_data_return_msg, root, false); // decoding...
36 IF (! Parsedok) // decoded failed
37 {
38 cout <"parsed error! /N "<users. Size (); index ++)
58 {
59 /*
60 in [for] circle, we must get user_info one by one, and fill in its value by values from JSON struct,
61 at last, push back into user_array to store the current user_info, then do again
62 */
63 user_info U;
64 U. ID = users [Index] ["ID"]. asint ();
65 U. Name = users [Index] ["name"]. asstring ();
66 gi. user_array.push_back (U );
67}
68
69 return gi;
70}
This is a typical piece of code for decoding a JSON string. The input and output of the function are clearly written in the comment. The following briefly analyzes the code.
1. parse, this function has been written in the preceding introduction. It is a function used to decode data in the string format called value. Then, it is used to determine the return value of the function. If the return value is false, JSON string decoding error.
2. After decoding is successful, it is the value returned by the operation. Here, for how to get the value in the value, the value class of jsoncpp provides two methods: one is the get function and the other is the [] Operator. I personally think it is still [] easy to use, the key in the JSON of the input parameter, you can obtain the value corresponding to the key
3. When an array is extracted, extract the elements one by one and use the value Conversion Function to extract the values. Value provides the asxxx function to convert values.
The above section briefly introduces the encoding and decoding functions in jsoncpp.