RapidJson Parsing (1)

Source: Internet
Author: User

Rapidjson Parsing (1)

Dionysoslai ([email protected]) 2014/9/20

Json is a lightweight data interchange format that is easy to read and write, and is easy for machine parsing and generation. Smaller than Xml,json, read and write faster, easier to parse. On the other hand, Rapidjson, as an upgraded version of JSON, has a better advantage in terms of efficiency.

JSON syntax rules

1. Data in name/value pairs

The writing format for JSON data: name/value pairs.

Name/value pairs include field names (in double quotes), followed by a colon, and then the value:

For example:

"Subject": "中文版"

The JSON value can be a number (integer or floating point), a string (in double quotation marks), a logical value (TRUE or false), an array (in square brackets), an object (in curly braces), and null.

A JSON object can contain multiple name/value pairs:

For example:

{"Subject": "中文版", "Subject": "Math"}

A JSON array can contain objects:

For example:

{"Student": [

{"Subject": "中文版", "Subject": "Math"},

{"Subject": "Yuwen", "Subject": "Music"},

]

}

2. Data is separated by commas

Note here that the last data does not add commas,

3. Curly braces are used to save objects

4. Square brackets are used to save the array


Rapdijson parsing

JSON itself is a JavaScript Object notation (Javascriptojbect Notation), which is easy to parse at the JavaScript level. For C + +, you must import the relevant library files. COCOS2DX introduced the Rapidjson Library from version 2.1, so here is Rapidjson parsing. The following is also based on the COCOS2DX engine (here is the version: COCOS2D-X-3.2RC0)

Before JSON parsing, you need to understand several related concepts of JSON:

Value:value is actually Var, which can be interpreted as int for value, as well as other data types such as String or bool variables. For the definition of value value, it is only a definition that has not yet determined its data type, and if it is clear value, its data type is determined accordingly.

The JSON data type is a map, expressed as the Key-value form, and there are several ways to convert the value to the underlying data type:

Vall. SetArray () Vall. Setarrayraw () Vall. Setbool () Vall. SetDouble () Vall. Setint ()

Vall. SetNull () Vall. SetObject () Vall. SetString () Vall. Setstringraw () Vall. Setuint ();

Vall. SetUint64 ()

Also, for the data type of value, it can be set repeatedly.


Write: Encode the value data into JSON appropriate data format;

Reader : In contrast to writer, the JSON format data is parsed into a value.

Json::readerreader;

1. Data analysis

First, here is a JSON file to parse: "Test.json", note that the JSON file format is generally "josn" as the suffix. At the same time the JSON file is encoded as: UTF-8 no BOM format. "Test.json" file with the following contents:

{

"Hello": "World",

"T": true,

"F": false,

"n": null,

"I": 123,

"PI": 3.1416,

"A": [

1,

2,

3,

4

]

}

Several commonly used data formats are included: string, bool, NULL, int, and so on.

Data read, parsed into JSON format

Data reads, regardless of the object's string or file form, or other forms, are ultimately represented as read-write string formats. If it is in file form, it is standard to read the file content.

Read file data:

        ssize_t size;unsigned char* ch = fileutils::getinstance ()->getfiledata ("Test.json", "R", &size); std::string data = std::string ((const char*) ch, size);

One thing to note here is that this cannot be written:

        std::string data = (const char*) ccfileutils::sharedfileutils ()->getfiledata ("Datatestqu.json", "R", &size);  < reading JSON files

This is because the format conversion has an error.

The next step is to parse the data into JSON format:

              Document Doc;                          < Create a Document object Rapidjson related operations are in the document class              doc. Parse<0> (Data.c_str ());               < parse the JSON data out through the parse method              if (Doc. Hasparseerror ())              {                            cclog ("getparseerror%s\n", Doc. Getparseerror ());              }

It is important to note that the parsed document (JSON parsed out in the form of XML DOM) to determine whether the resolution is correct, otherwise all subsequent processing is invalid.

JSON data read and change------to-value operations

For data read and value change, the basic idea: Read the value of the key by value, determine the key value type, according to the key value type, the corresponding method for output and value change operation. The relevant code is as follows:

              rapidjson::value& valstring =doc["Hello"];                            < reads the value of the key "Hello", according to our JSON document, is a string if (Valstring.isstring ())///< to determine if it is a string {                            CONST char* CH =valstring.getstring ();                            Log (CH);                            Log (valstring.getstring ());                            Valstring.setstring ("newstring");              Log (valstring.getstring ());       } rapidjson::value& ValArray =doc["a"]; < reads the key "a" value, according to our JSON document, is an array if (Valarray.isarray ())///< determines whether the type of Val is an array of our tollgate keys corresponding to the VA                            Lue actual array {for (int i = 0; i< valarray.capacity (); ++i) {Rapidjson::value&first = Valarray[i];///< gets to the first element root in Val According to our JSON file Val There are 4 elements cclog ("%f", first.                     GetDouble ()); < converting value to a double type prints out the result of 0.5 first.                                          SetDouble (10.F); Cclog ("%f", first.                     GetDouble ()); < converting value to a double type prints out a result of 0.5S}}


JSON data manipulation----to key operations

1. Adding a Member Object

For a member object, it must be in the Key-value format. Therefore, be clear about the value of key and value. Adds a member object that, under the DOM data that was originally parsed by JSON, allocates space for the member variable, and then adds the member object in.

Add string objects, null objects, and array objects as follows:

              Add a String object; Rapidjson::D ocument::allocatortype&allocator = doc.   Getallocator ();                                                                  < get the initial data of the allocator Rapidjson::value strobject (rapidjson::kstringtype);              < add string Method 1 strobject.setstring ("Love"); Doc. AddMember ("Hello1", strobject,allocator);/* Doc.                                                                                    AddMember ("Hello1", "Love You", allocator); < add String Method 2: Add an object to the allocator//////////Add a Null object Rapidjson::value Nullobject (rapidjson::knullt              YPE); Doc.                                                                            AddMember ("null", Nullobject,allocator);                 < add an object to the allocator///Add an Array object Rapidjson::value array (rapidjson::karraytype);     < Create an array of Objects Rapidjson::value object (Rapidjson::kobjecttype);          < Create an array of objects inside. Object.              AddMember ("id", 1,allocator); Object.              AddMember ("name", "Lai", allocator); Object.              AddMember ("Age", "n", allocator); Object.              AddMember ("Low", true,allocator); Array.              Pushback (object, allocator); Doc.                                     AddMember ("Player", array,allocator); < add the above array contents to an array named "Player"////Add a member object to an existing array rapidjson::value& aArray1 = doc["a"]              ; Aarray1.pushback (2.0, allocator);


2. Change the name of the key that is key

This won't

3. Delete a member object

The Member object Delete method has a uniform method: RemoveMember, for an array object, you can use the Popback method if you want to delete the last element. Examples are as follows:

              Delete an array member object inside              the element rapidjson::value& aArray2 = doc["a"];        < reads the key "a" value, according to our JSON document, is an array of              aarray2.popback ();                < Delete array last member object               if (Doc. RemoveMember ("I"))                                                       ///< Delete the member variable              {                            log ("Delet imember ok!") with the key "I";              }


Writing JSON data to a file

The Write interface mentioned above is called to encode the value data into a JSON-appropriate data format, where the data is written to a file. Examples are as follows:

              Write the JSON data back into the file---Delete the file before writing to the content              rapidjson::stringbuffer  buffer;              Rapidjson::writer<rapidjson::stringbuffer>writer (buffer);              Doc. Accept (writer);                               #if (cc_target_platform== cc_platform_win32)                   system ("dele:\cocos2d-x-3.2rc0\tests\cpp-empty-test\resources\ Test.josn ");                           < first delete the file---before the file read data, so make sure that the file exists              file* file = fopen ("Test.json", "WB");               if (file)              {                            fputs (buffer. GetString (), file);                            fclose (file);              }             #else if (cc_target_platform== cc_platform_android)///The              principle is similar, is to first empty the file, in writing. It's not written here.             #endif


This concludes the article "RapidJson (1)". Almost all operations that involve basic JSON, from data parsing, key-value changes, data re-writes, and so on. The last problem is "change the name of the key", the current problem did not find a good way, do not know who has good ideas can @ I, greatly appreciated! Some code-related addresses can be seen on my git: https://github.com/DionysosLai/Coco2d-xRes/tree/master/Function%20%E5%8A%9F%E8%83%BD%E5 %ae%9e%e7%8e%b0/rapidjson

RapidJson Parsing (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.